Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import tensorflow as tf
|
3 |
+
from PIL import Image
|
4 |
+
import numpy as np
|
5 |
+
# from .modules.tools import Analysing_image, text_to_speech
|
6 |
+
from gtts import gTTS
|
7 |
+
from transformers import BioGptTokenizer, AutoModelForCausalLM, pipeline
|
8 |
+
from deep_translator import GoogleTranslator
|
9 |
+
import tempfile
|
10 |
+
import os
|
11 |
+
# Set the page configuration
|
12 |
+
|
13 |
+
|
14 |
+
def Analysing_image(st, model, image_file):
|
15 |
+
try:
|
16 |
+
# Open and display the image
|
17 |
+
image = Image.open(image_file)
|
18 |
+
st.image(image, caption="Uploaded Image", use_column_width=True)
|
19 |
+
|
20 |
+
# Preprocess the image:
|
21 |
+
# Ensure it is resized to the input dimensions your model expects (150x150 in this example)
|
22 |
+
img_resized = image.resize((150, 150))
|
23 |
+
img_array = np.array(img_resized).astype('float32') / 255.0
|
24 |
+
|
25 |
+
# If the image is not 3 channels (some images might be grayscale), repeat channels if necessary
|
26 |
+
if img_array.ndim == 2:
|
27 |
+
img_array = np.stack((img_array,)*3, axis=-1)
|
28 |
+
elif img_array.shape[2] == 1:
|
29 |
+
img_array = np.concatenate([img_array]*3, axis=-1)
|
30 |
+
|
31 |
+
# Add batch dimension
|
32 |
+
img_batch = np.expand_dims(img_array, axis=0)
|
33 |
+
|
34 |
+
# Run prediction
|
35 |
+
predictions = model.predict(img_batch)
|
36 |
+
|
37 |
+
st.write("Prediction probabilities:", predictions)
|
38 |
+
|
39 |
+
# Assuming a multi-class classification where the class with the highest probability is selected:
|
40 |
+
predicted_class = np.argmax(predictions, axis=1)
|
41 |
+
st.write("Predicted class index:", predicted_class[0])
|
42 |
+
return predicted_class
|
43 |
+
except:
|
44 |
+
return None
|
45 |
+
|
46 |
+
# Function to convert text to speech
|
47 |
+
def text_to_speech(text):
|
48 |
+
tts = gTTS(text)
|
49 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
|
50 |
+
tts.save(temp_file.name)
|
51 |
+
return temp_file.name
|
52 |
+
|
53 |
+
@st.cache_resource # Cache the model to avoid reloading on every interaction
|
54 |
+
def load_generator():
|
55 |
+
# Use a medical-specific model like BioGPT or a general-purpose model like GPT-2
|
56 |
+
tokenizer = BioGptTokenizer.from_pretrained("microsoft/BioGPT")
|
57 |
+
model = AutoModelForCausalLM.from_pretrained("microsoft/BioGPT")
|
58 |
+
return model, tokenizer
|
59 |
+
|
60 |
+
@st.cache_resource # Cache the model to avoid reloading on every interaction
|
61 |
+
def load_summarizer():
|
62 |
+
# Use a summarization model like "facebook/bart-large-cnn"
|
63 |
+
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
|
64 |
+
return summarizer
|
65 |
+
|
66 |
+
generator, tokenizer = load_generator()
|
67 |
+
summarizer = load_summarizer()
|
68 |
+
|
69 |
+
st.set_page_config(page_title="Medical Image Classifier & Chatbot", layout="wide")
|
70 |
+
|
71 |
+
st.title("Medical Image Classifier & Chatbot")
|
72 |
+
st.sidebar.header("Medical Analysis")
|
73 |
+
image_file = st.sidebar.file_uploader("Upload an Image (.jpg, .jpeg, .png)", type=["jpg", "jpeg", "png"])
|
74 |
+
# Create tabs for each functionality
|
75 |
+
tab1, tab2, tab3, tab4 = st.tabs(["Classification", "Chatbot", "Translation & Summary", "Audio"])
|
76 |
+
predict_class = None
|
77 |
+
Summary = None
|
78 |
+
|
79 |
+
with tab1:
|
80 |
+
# st.write("Upload your finalized model and an image to classify.")
|
81 |
+
# Sidebar for uploading files
|
82 |
+
model_file = st.sidebar.file_uploader("Upload your Keras model (.h5 file)", type=["h5"])
|
83 |
+
# Check if a model has been uploaded
|
84 |
+
if model_file is not None:
|
85 |
+
# Save the uploaded model file to disk
|
86 |
+
with open("uploaded_model.h5", "wb") as f:
|
87 |
+
f.write(model_file.getbuffer())
|
88 |
+
st.sidebar.success("Model uploaded successfully!")
|
89 |
+
|
90 |
+
# Attempt to load the model
|
91 |
+
try:
|
92 |
+
model = tf.keras.models.load_model("uploaded_model.h5")
|
93 |
+
st.sidebar.info("Model loaded successfully!")
|
94 |
+
except Exception as e:
|
95 |
+
st.sidebar.error("Error loading model: " + str(e))
|
96 |
+
st.stop()
|
97 |
+
|
98 |
+
# Check if an image has been uploaded
|
99 |
+
if image_file is not None:
|
100 |
+
predict_class = Analysing_image(st, model, image_file)
|
101 |
+
else:
|
102 |
+
st.info("Please upload an image to classify.")
|
103 |
+
else:
|
104 |
+
st.info("Using Pretrained model")
|
105 |
+
model = tf.keras.models.load_model("./models/medical_classifier.h5")
|
106 |
+
if image_file is not None:
|
107 |
+
predict_class = Analysing_image(st, model, image_file)
|
108 |
+
else:
|
109 |
+
st.info("Please upload an image to classify.")
|
110 |
+
# -----------------------------------------------------------------------------------------------
|
111 |
+
|
112 |
+
with tab2:
|
113 |
+
if predict_class is not None:
|
114 |
+
# Create a prompt for the model
|
115 |
+
prompt = f"What is {predict_class} in medical terms?"
|
116 |
+
# Generate text using the Hugging Face model
|
117 |
+
with st.spinner("Generating description..."):
|
118 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
119 |
+
# Générer du texte
|
120 |
+
output = generator.generate(
|
121 |
+
inputs["input_ids"],
|
122 |
+
max_length=200, # Longueur maximale du texte généré
|
123 |
+
num_return_sequences=1, # Nombre de séquences à générer
|
124 |
+
no_repeat_ngram_size=2, # Éviter la répétition de phrases
|
125 |
+
top_k=50, # Contrôle la diversité du texte
|
126 |
+
top_p=0.95, # Contrôle la qualité du texte
|
127 |
+
temperature=0.7, # Contrôle la créativité du texte
|
128 |
+
)
|
129 |
+
|
130 |
+
# Décoder et afficher le texte généré
|
131 |
+
# generated_text = tokenizer.decode(output[0], skip_special_tokens=True)
|
132 |
+
output = tokenizer.decode(output[0], skip_special_tokens=True)
|
133 |
+
# output = generator(prompt, max_length=200, num_return_sequences=1)
|
134 |
+
# st.session_state.chat_response = output[0]['generated_text']
|
135 |
+
st.session_state.chat_response = output
|
136 |
+
# Display the generated description
|
137 |
+
st.subheader("Generated Description:")
|
138 |
+
st.write(st.session_state.chat_response)
|
139 |
+
|
140 |
+
|
141 |
+
# Add translation functionality
|
142 |
+
with tab3:
|
143 |
+
st.header("Translation to German & Summary")
|
144 |
+
if 'chat_response' in st.session_state and st.session_state.chat_response:
|
145 |
+
medical_terms = st.session_state.chat_response
|
146 |
+
# Translate to German
|
147 |
+
translator = GoogleTranslator(source='en', target='de')
|
148 |
+
german_translation = translator.translate(medical_terms)
|
149 |
+
|
150 |
+
# Create summary (simple example - in practice you might want to use a more sophisticated summarization method)
|
151 |
+
# summary = " ".join(st.session_state.chat_response.split()[:30]) + "..."
|
152 |
+
st.write("German Translation:", german_translation)
|
153 |
+
|
154 |
+
if st.button("Generate Summary"):
|
155 |
+
if medical_terms:
|
156 |
+
# Create a prompt for the model
|
157 |
+
prompt = f"{predict_class} is a medical condition that refers to "
|
158 |
+
# Generate a summary using the Hugging Face model
|
159 |
+
with st.spinner("Generating summary..."):
|
160 |
+
# Summarize the prompt (you can adjust max_length and min_length)
|
161 |
+
summary = summarizer(prompt, max_length=60, min_length=25, do_sample=False)
|
162 |
+
# Display the generated summary
|
163 |
+
st.subheader("Generated Summary:")
|
164 |
+
st.write(summary[0]['summary_text'])
|
165 |
+
else:
|
166 |
+
st.warning("Please enter a medical term.")
|
167 |
+
|
168 |
+
else:
|
169 |
+
st.info("No chatbot response available for translation and summary.")
|
170 |
+
|
171 |
+
|
172 |
+
# Add audio functionality
|
173 |
+
with tab4:
|
174 |
+
st.header("Audio Output")
|
175 |
+
if 'chat_response' in st.session_state and st.session_state.chat_response:
|
176 |
+
# Convert chatbot response to audio
|
177 |
+
audio_file = text_to_speech(st.session_state.chat_response)
|
178 |
+
st.audio(audio_file)
|
179 |
+
# Clean up temp file
|
180 |
+
with open(audio_file, "rb") as file:
|
181 |
+
btn = st.download_button(
|
182 |
+
label="Download audio",
|
183 |
+
data=file,
|
184 |
+
file_name="chat_response.mp3",
|
185 |
+
mime="audio/mpeg"
|
186 |
+
)
|
187 |
+
os.unlink(audio_file)
|
188 |
+
else:
|
189 |
+
st.info("No chatbot response available for audio conversion.")
|
190 |
+
|
191 |
+
|
192 |
+
|
193 |
+
print("Streamlit app updated with translation, summarization, and audio features.")
|