Update app.py
Browse files
app.py
CHANGED
@@ -36,10 +36,10 @@ def predict_demo(image, model_name):
|
|
36 |
|
37 |
# مدل اول
|
38 |
def load_model():
|
39 |
-
model = tf.keras.models.load_model("model.h5", compile=False)
|
40 |
model.compile(optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=0.00001, decay=0.0001),
|
41 |
metrics=["accuracy"], loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.1))
|
42 |
-
model.load_weights("modeldense1.h5")
|
43 |
return model
|
44 |
|
45 |
model = load_model()
|
@@ -76,7 +76,7 @@ def predict_demo(image, model_name):
|
|
76 |
elif model_name == "what kind is":
|
77 |
image = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)
|
78 |
im_pil = Image.fromarray(image)
|
79 |
-
pipe = pipeline("image-classification", model="DHEIVER/finetuned-BreastCancer-Classification")
|
80 |
|
81 |
def predict(image):
|
82 |
result = pipe(image)
|
@@ -110,22 +110,18 @@ def generate_fixed_size_chart(predictions, image_file, chart_width=6, chart_heig
|
|
110 |
axes[i].set_title(f'{model_name}')
|
111 |
|
112 |
# ذخیرهی نمودار در فایل
|
113 |
-
chart_path = f"
|
114 |
plt.savefig(chart_path, bbox_inches='tight')
|
115 |
plt.close(fig)
|
116 |
|
117 |
return chart_path
|
118 |
|
119 |
-
# استفاده از pdfkit برای تولید PDF
|
120 |
def generate_pdf(patient_info, predictions):
|
121 |
all_charts = []
|
122 |
for image_file, prediction in predictions:
|
123 |
chart = generate_fixed_size_chart(prediction, image_file)
|
124 |
all_charts.append(chart)
|
125 |
|
126 |
-
# تبدیل مسیر نسبی به مسیر مطلق
|
127 |
-
image_path = str(Path(patient_info.get('ImagePath', '')).resolve())
|
128 |
-
|
129 |
# تولید محتوای HTML برای PDF
|
130 |
html_content = f"""
|
131 |
<html>
|
@@ -155,7 +151,7 @@ def generate_pdf(patient_info, predictions):
|
|
155 |
<h1>Patient Report</h1>
|
156 |
<div class="image-container">
|
157 |
<h3>Patient Image:</h3>
|
158 |
-
<img src="{
|
159 |
</div>
|
160 |
<div class="image-container">
|
161 |
<h3>Patient Information:</h3>
|
@@ -170,17 +166,11 @@ def generate_pdf(patient_info, predictions):
|
|
170 |
"""
|
171 |
|
172 |
# # تنظیمات PDF
|
173 |
-
pdf_path = "patient_report.pdf"
|
174 |
-
# config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltopdf')
|
175 |
-
# options = {
|
176 |
-
# "enable-local-file-access": True,
|
177 |
-
# "no-stop-slow-scripts": True,
|
178 |
-
# }
|
179 |
-
# pdfkit.from_string(html_content, pdf_path, configuration=config, options=options)
|
180 |
|
181 |
html = HTML(string= html_content, base_url="/app")
|
182 |
html.write_pdf(pdf_path)
|
183 |
-
|
184 |
return pdf_path
|
185 |
|
186 |
|
@@ -188,18 +178,34 @@ def generate_pdf(patient_info, predictions):
|
|
188 |
# تابع نمایش گزارش و تولید PDF
|
189 |
def display_report(patient_info, predictions):
|
190 |
pdf_path = generate_pdf(patient_info, predictions)
|
191 |
-
report_content = f"<h2>Patient Report
|
192 |
return report_content, pdf_path
|
193 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
194 |
|
195 |
# رابط Gradio
|
196 |
with gr.Blocks() as demo:
|
197 |
gr.Markdown("## Breast Cancer Detection - Multi-Model Interface")
|
198 |
|
199 |
-
tab_index = gr.State(0) # انتخاب تب پیشفرض
|
200 |
-
|
201 |
# صفحه اول - اطلاعات بیمار
|
202 |
-
with gr.
|
203 |
patient_image = gr.Image(label="Upload Patient Profile Image", type="pil")
|
204 |
name = gr.Textbox(label="Name")
|
205 |
height = gr.Number(label="Height (cm)")
|
@@ -211,24 +217,28 @@ with gr.Blocks() as demo:
|
|
211 |
occupation = gr.Textbox(label="Occupation")
|
212 |
medical_history = gr.Textbox(label="Medical History")
|
213 |
patient_info = gr.State()
|
214 |
-
|
|
|
215 |
|
216 |
# صفحه دوم - انتخاب مدلها و آپلود تصاویر ماموگرافی
|
217 |
-
with gr.Tab("Model & Image Selection")
|
218 |
model_choice = gr.CheckboxGroup(["how dense is", "what kind is"], label="Select Model(s)", interactive=True)
|
219 |
mammography_images = gr.File(label="Upload Mammography Image(s)", file_count="multiple", type="filepath")
|
220 |
predictions = gr.State()
|
221 |
process_button = gr.Button("Process Images")
|
|
|
|
|
|
|
222 |
|
223 |
# صفحه سوم - نمایش اطلاعات و پیشبینی
|
224 |
-
with gr.Tab("Results")
|
225 |
report_display = gr.HTML(label="Patient Report")
|
226 |
download_button = gr.Button("Download Report")
|
227 |
|
228 |
# جمعآوری اطلاعات بیمار و انتقال به مرحله بعدی
|
229 |
def collect_patient_info(image, name, height, weight, age, gender, residence, birth_place, occupation, medical_history):
|
230 |
# ذخیره تصویر بیمار و اضافه کردن مسیر به اطلاعات بیمار
|
231 |
-
image_path = "patient_image.jpg"
|
232 |
image.save(image_path)
|
233 |
return {
|
234 |
"Name": name,
|
@@ -241,37 +251,23 @@ with gr.Blocks() as demo:
|
|
241 |
"Occupation": occupation,
|
242 |
"Medical History": medical_history,
|
243 |
"ImagePath": image_path # اضافه کردن مسیر تصویر
|
244 |
-
}
|
245 |
|
246 |
patient_info_submit.click(
|
247 |
collect_patient_info,
|
248 |
inputs=[patient_image, name, height, weight, age, gender, residence, birth_place, occupation, medical_history],
|
249 |
-
outputs=patient_info
|
250 |
-
).then(
|
251 |
-
lambda: gr.update(visible=True), # انتقال به تب دوم
|
252 |
-
inputs=[],
|
253 |
-
outputs=tabs2
|
254 |
)
|
255 |
|
256 |
-
# پردازش تصاویر ماموگرافی با مدلهای انتخابی
|
257 |
-
def process_images(patient_info, selected_models, images):
|
258 |
-
all_predictions = []
|
259 |
-
for image_file in images:
|
260 |
-
image = Image.open(image_file)
|
261 |
-
image_predictions = {model: predict_demo(image, model) for model in selected_models}
|
262 |
-
all_predictions.append((image_file, image_predictions))
|
263 |
-
return all_predictions
|
264 |
|
265 |
process_button.click(
|
266 |
process_images,
|
267 |
inputs=[patient_info, model_choice, mammography_images],
|
268 |
-
outputs=predictions
|
269 |
-
).then(
|
270 |
-
lambda: gr.update(visible=True), # انتقال به تب دوم
|
271 |
-
inputs=[],
|
272 |
-
outputs=tabs3
|
273 |
)
|
274 |
|
|
|
|
|
275 |
# نمایش گزارش بیمار و پیشبینیها در صفحه سوم
|
276 |
download_button.click(
|
277 |
display_report,
|
@@ -279,4 +275,4 @@ with gr.Blocks() as demo:
|
|
279 |
outputs=[report_display, gr.File(label="Download PDF Report")] # اصلاح خروجی برای Gradio
|
280 |
)
|
281 |
|
282 |
-
demo.launch(debug=True)
|
|
|
36 |
|
37 |
# مدل اول
|
38 |
def load_model():
|
39 |
+
model = tf.keras.models.load_model("/content/model.h5", compile=False)
|
40 |
model.compile(optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=0.00001, decay=0.0001),
|
41 |
metrics=["accuracy"], loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.1))
|
42 |
+
model.load_weights("/content/modeldense1.h5")
|
43 |
return model
|
44 |
|
45 |
model = load_model()
|
|
|
76 |
elif model_name == "what kind is":
|
77 |
image = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)
|
78 |
im_pil = Image.fromarray(image)
|
79 |
+
pipe = pipeline("image-classification", model="DHEIVER/finetuned-BreastCancer-Classification", device=0)
|
80 |
|
81 |
def predict(image):
|
82 |
result = pipe(image)
|
|
|
110 |
axes[i].set_title(f'{model_name}')
|
111 |
|
112 |
# ذخیرهی نمودار در فایل
|
113 |
+
chart_path = f"/content/{os.path.basename(image_file)}_combined_chart.png"
|
114 |
plt.savefig(chart_path, bbox_inches='tight')
|
115 |
plt.close(fig)
|
116 |
|
117 |
return chart_path
|
118 |
|
|
|
119 |
def generate_pdf(patient_info, predictions):
|
120 |
all_charts = []
|
121 |
for image_file, prediction in predictions:
|
122 |
chart = generate_fixed_size_chart(prediction, image_file)
|
123 |
all_charts.append(chart)
|
124 |
|
|
|
|
|
|
|
125 |
# تولید محتوای HTML برای PDF
|
126 |
html_content = f"""
|
127 |
<html>
|
|
|
151 |
<h1>Patient Report</h1>
|
152 |
<div class="image-container">
|
153 |
<h3>Patient Image:</h3>
|
154 |
+
<img src="{patient_info.get('ImagePath', '')}" alt="Patient Image" style="width: 300px; height: auto;">
|
155 |
</div>
|
156 |
<div class="image-container">
|
157 |
<h3>Patient Information:</h3>
|
|
|
166 |
"""
|
167 |
|
168 |
# # تنظیمات PDF
|
169 |
+
pdf_path = "/content/patient_report.pdf"
|
|
|
|
|
|
|
|
|
|
|
|
|
170 |
|
171 |
html = HTML(string= html_content, base_url="/app")
|
172 |
html.write_pdf(pdf_path)
|
173 |
+
|
174 |
return pdf_path
|
175 |
|
176 |
|
|
|
178 |
# تابع نمایش گزارش و تولید PDF
|
179 |
def display_report(patient_info, predictions):
|
180 |
pdf_path = generate_pdf(patient_info, predictions)
|
181 |
+
report_content = f"<h2>Patient Report.</h2><p>{patient_info}</p><h2>Predictions</h2>{predictions}"
|
182 |
return report_content, pdf_path
|
183 |
|
184 |
+
# پردازش تصاویر ماموگرافی با مدلهای انتخابی
|
185 |
+
def process_images(patient_info, selected_models, images):
|
186 |
+
all_predictions = []
|
187 |
+
total_images = len(images)
|
188 |
+
|
189 |
+
# حلقه برای پردازش تصاویر
|
190 |
+
for idx, image_file in enumerate(images):
|
191 |
+
# بهروزرسانی وضعیت پردازش
|
192 |
+
status = f"Processing Image {idx + 1} of {total_images}..."
|
193 |
+
yield all_predictions, status # خروجی موقت
|
194 |
+
|
195 |
+
image = Image.open(image_file)
|
196 |
+
image_predictions = {model: predict_demo(image, model) for model in selected_models}
|
197 |
+
all_predictions.append((image_file, image_predictions))
|
198 |
+
|
199 |
+
# پس از اتمام پردازش
|
200 |
+
final_status = "Processing Complete!"
|
201 |
+
yield all_predictions, final_status # خروجی نهایی
|
202 |
|
203 |
# رابط Gradio
|
204 |
with gr.Blocks() as demo:
|
205 |
gr.Markdown("## Breast Cancer Detection - Multi-Model Interface")
|
206 |
|
|
|
|
|
207 |
# صفحه اول - اطلاعات بیمار
|
208 |
+
with gr.Tab("Patient Info"):
|
209 |
patient_image = gr.Image(label="Upload Patient Profile Image", type="pil")
|
210 |
name = gr.Textbox(label="Name")
|
211 |
height = gr.Number(label="Height (cm)")
|
|
|
217 |
occupation = gr.Textbox(label="Occupation")
|
218 |
medical_history = gr.Textbox(label="Medical History")
|
219 |
patient_info = gr.State()
|
220 |
+
snackbar = gr.HTML("<div style='color: green; font-weight: bold;'> Patient information was saved </div>", visible=False) # پیام snackbar
|
221 |
+
patient_info_submit = gr.Button("Save")
|
222 |
|
223 |
# صفحه دوم - انتخاب مدلها و آپلود تصاویر ماموگرافی
|
224 |
+
with gr.Tab("Model & Image Selection"):
|
225 |
model_choice = gr.CheckboxGroup(["how dense is", "what kind is"], label="Select Model(s)", interactive=True)
|
226 |
mammography_images = gr.File(label="Upload Mammography Image(s)", file_count="multiple", type="filepath")
|
227 |
predictions = gr.State()
|
228 |
process_button = gr.Button("Process Images")
|
229 |
+
# المان برای نمایش وضعیت پردازش
|
230 |
+
status_box = gr.Textbox(label="Processing Status", interactive=False)
|
231 |
+
|
232 |
|
233 |
# صفحه سوم - نمایش اطلاعات و پیشبینی
|
234 |
+
with gr.Tab("Results"):
|
235 |
report_display = gr.HTML(label="Patient Report")
|
236 |
download_button = gr.Button("Download Report")
|
237 |
|
238 |
# جمعآوری اطلاعات بیمار و انتقال به مرحله بعدی
|
239 |
def collect_patient_info(image, name, height, weight, age, gender, residence, birth_place, occupation, medical_history):
|
240 |
# ذخیره تصویر بیمار و اضافه کردن مسیر به اطلاعات بیمار
|
241 |
+
image_path = "/content/patient_image.jpg"
|
242 |
image.save(image_path)
|
243 |
return {
|
244 |
"Name": name,
|
|
|
251 |
"Occupation": occupation,
|
252 |
"Medical History": medical_history,
|
253 |
"ImagePath": image_path # اضافه کردن مسیر تصویر
|
254 |
+
}, gr.update(visible=True) # نمایش snackbar و مخفی شدن آن پس از 3 ثانیه
|
255 |
|
256 |
patient_info_submit.click(
|
257 |
collect_patient_info,
|
258 |
inputs=[patient_image, name, height, weight, age, gender, residence, birth_place, occupation, medical_history],
|
259 |
+
outputs=[patient_info, snackbar] # نمایش اطلاعات و snackbar
|
|
|
|
|
|
|
|
|
260 |
)
|
261 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
262 |
|
263 |
process_button.click(
|
264 |
process_images,
|
265 |
inputs=[patient_info, model_choice, mammography_images],
|
266 |
+
outputs=[predictions, status_box] # دو خروجی تنظیم شده است
|
|
|
|
|
|
|
|
|
267 |
)
|
268 |
|
269 |
+
|
270 |
+
|
271 |
# نمایش گزارش بیمار و پیشبینیها در صفحه سوم
|
272 |
download_button.click(
|
273 |
display_report,
|
|
|
275 |
outputs=[report_display, gr.File(label="Download PDF Report")] # اصلاح خروجی برای Gradio
|
276 |
)
|
277 |
|
278 |
+
demo.launch(debug=True, share=True)
|