aminahmadi0101 commited on
Commit
e50db3f
·
verified ·
1 Parent(s): 1aa50ce

Upload 6 files

Browse files
README.md CHANGED
@@ -1,14 +1,14 @@
1
- ---
2
- title: Clinical Decision Aid Mammogram
3
- emoji: 💻
4
- colorFrom: purple
5
- colorTo: green
6
- sdk: gradio
7
- sdk_version: 5.7.1
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- short_description: Diagnosis of breast type in breast cancer from mammography
12
- ---
13
-
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ ---
2
+ title: Clinical Decision Aid Mammogram
3
+ emoji: 💻
4
+ colorFrom: purple
5
+ colorTo: green
6
+ sdk: gradio
7
+ sdk_version: 5.7.1
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ short_description: Diagnosis of breast type in breast cancer from mammography
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pdfkit
2
+ # path_wkhtmltopdf = "/usr/bin/wkhtmltopdf"
3
+ # config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
4
+ import subprocess
5
+
6
+ try:
7
+ path_wkhtmltopdf = subprocess.check_output(['which', 'wkhtmltopdf']).decode('utf-8').strip()
8
+ config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
9
+ except subprocess.CalledProcessError:
10
+ raise FileNotFoundError("wkhtmltopdf not found. Ensure it is installed in your environment.")
11
+
12
+
13
+ # import tensorflow as tf
14
+ import numpy as np
15
+ from PIL import Image
16
+ import cv2
17
+ import gradio as gr
18
+ # from numpy import asarray
19
+ from transformers import pipeline
20
+
21
+ from tensorflow.keras.layers import Dense, Flatten, GlobalAveragePooling2D, BatchNormalization, Dropout,AveragePooling2D
22
+ import tensorflow as tf
23
+ from tensorflow.keras.applications import DenseNet201
24
+ from keras.models import Model
25
+ from keras.models import Sequential
26
+ from keras.regularizers import *
27
+ from tensorflow import keras
28
+ from tensorflow.keras import layers
29
+
30
+ import tensorflow as tf
31
+ import matplotlib.pyplot as plt
32
+ from PIL import Image
33
+ import cv2
34
+ from transformers import pipeline
35
+ import os
36
+
37
+ # تابع پیش‌بینی
38
+ def predict_demo(image, model_name):
39
+ if model_name == "how dense is":
40
+ image = np.asarray(image)
41
+
42
+ # مدل اول
43
+ def load_model():
44
+ model = tf.keras.models.load_model("model.h5", compile=False)
45
+ model.compile(optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=0.00001, decay=0.0001),
46
+ metrics=["accuracy"], loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.1))
47
+ model.load_weights("modeldense1.h5")
48
+ return model
49
+
50
+ model = load_model()
51
+
52
+ def preprocess(image):
53
+ image = cv2.resize(image, (224, 224))
54
+ kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
55
+ im = cv2.filter2D(image, -1, kernel)
56
+ if im.ndim == 3:
57
+ # اضافه کردن بعد جدید برای ورودی مدل
58
+ im = np.expand_dims(im, axis=0)
59
+ elif im.ndim == 2:
60
+ # اگر تصویر سیاه و سفید باشد
61
+ im = np.expand_dims(im, axis=-1)
62
+ im = np.repeat(im, 3, axis=-1)
63
+ im = np.expand_dims(im, axis=0)
64
+ return im
65
+
66
+
67
+ class_name = ['Benign with Density=1', 'Malignant with Density=1', 'Benign with Density=2',
68
+ 'Malignant with Density=2', 'Benign with Density=3', 'Malignant with Density=3',
69
+ 'Benign with Density=4', 'Malignant with Density=4']
70
+
71
+ def predict_img(img):
72
+ img = preprocess(img)
73
+ img = img / 255.0
74
+ pred = model.predict(img)[0]
75
+ return {class_name[i]: float(pred[i]) for i in range(8)}
76
+
77
+
78
+ predict_mamo= predict_img(image)
79
+ return predict_mamo
80
+
81
+ elif model_name == "what kind is":
82
+ image = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)
83
+ im_pil = Image.fromarray(image)
84
+ pipe = pipeline("image-classification", model="DHEIVER/finetuned-BreastCancer-Classification", device=0)
85
+
86
+ def predict(image):
87
+ result = pipe(image)
88
+ return {result[i]['label']: float(result[i]['score']) for i in range(2)}
89
+
90
+ return predict(im_pil)
91
+
92
+
93
+
94
+ def generate_fixed_size_chart(predictions, image_file, chart_width=6, chart_height=5):
95
+ # بارگذاری تصویر ماموگرافی
96
+ mammo_image = plt.imread(image_file)
97
+
98
+ # تعداد مدل‌ها
99
+ num_models = len(predictions)
100
+
101
+ # ایجاد figure با تنظیم عرض و ارتفاع هر زیرنمودار
102
+ fig, axes = plt.subplots(1, num_models + 1, figsize=(chart_width * (num_models + 1), chart_height), constrained_layout=True)
103
+ # fig.subplots_adjust(wspace=0.7) # فاصله ثابت بین نمودارها
104
+
105
+ # نمایش تصویر ماموگرافی در subplot اول
106
+ axes[0].imshow(mammo_image, cmap='gray')
107
+ axes[0].axis('off')
108
+ axes[0].set_title("Mammogram")
109
+
110
+ # ایجاد نمودارهای پیش‌بینی برای هر مدل در subplots بعدی
111
+ for i, (model_name, prediction) in enumerate(predictions.items(), start=1):
112
+ labels, values = zip(*prediction.items())
113
+ axes[i].barh(labels, values, color='skyblue')
114
+ axes[i].set_xlabel('Probability (%)')
115
+ axes[i].set_title(f'{model_name}')
116
+
117
+ # ذخیره‌ی نمودار در فایل
118
+ chart_path = f"{os.getcwd()}/{os.path.basename(image_file)}_combined_chart.png"
119
+ plt.savefig(chart_path, bbox_inches='tight')
120
+ plt.close(fig)
121
+
122
+ return chart_path
123
+
124
+ def generate_pdf(patient_info, predictions):
125
+ all_charts = []
126
+ for image_file, prediction in predictions:
127
+ chart = generate_fixed_size_chart(prediction, image_file)
128
+ all_charts.append(chart)
129
+
130
+ # تولید محتوای HTML برای PDF
131
+ html_content = f"""
132
+ <html>
133
+ <head>
134
+ <style>
135
+ body {{ font-family: Arial, sans-serif; }}
136
+ h1 {{ color: #2F4F4F; text-align: center; margin-bottom: 30px; }}
137
+ .info-container {{
138
+ display: flex;
139
+ flex-wrap: wrap;
140
+ justify-content: space-between;
141
+ margin-bottom: 20px;
142
+ }}
143
+ .info-item {{
144
+ width: 45%;
145
+ margin-bottom: 10px;
146
+ }}
147
+ .image-container {{
148
+ text-align: center;
149
+ margin-bottom: 50px;
150
+ }}
151
+ </style>
152
+ </head>
153
+ <body>
154
+ <h1>Patient Report</h1>
155
+ <div class="image-container">
156
+ <h3>Patient Image:</h3>
157
+ <img src="{patient_info.get('ImagePath', '')}" alt="Patient Image" width="300">
158
+ </div>
159
+ <div class="image-container">
160
+ <h3>Patient Information:</h3>
161
+ <div class="info-container">
162
+ {"".join(f"<div class='info-item'><strong>{key}:</strong> {value if value else '-'}</div>" for key, value in patient_info.items() if key != "ImagePath")}
163
+ </div>
164
+ </div>
165
+ <h3>Predictions:</h3>
166
+ {"".join(f"<div ><img src='{chart}' width='80%'></div>" for chart in all_charts)}
167
+ </body>
168
+ </html>
169
+ """
170
+
171
+ # تنظیمات PDF
172
+ pdf_path = "patient_report.pdf"
173
+ config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltopdf')
174
+ options = {
175
+ "enable-local-file-access": True,
176
+ "no-stop-slow-scripts": True,
177
+ }
178
+ pdfkit.from_string(html_content, pdf_path, configuration=config, options=options)
179
+
180
+ return pdf_path
181
+
182
+
183
+
184
+ # تابع نمایش گزارش و تولید PDF
185
+ def display_report(patient_info, predictions):
186
+ pdf_path = generate_pdf(patient_info, predictions)
187
+ report_content = f"<h2>Patient Report</h2><p>{patient_info}</p><h2>Predictions</h2>{predictions}"
188
+ return report_content, pdf_path
189
+
190
+ # رابط Gradio
191
+ with gr.Blocks() as demo:
192
+ gr.Markdown("## Breast Cancer Detection - Multi-Model Interface")
193
+
194
+ # صفحه اول - اطلاعات بیمار
195
+ with gr.Tab("Patient Info"):
196
+ patient_image = gr.Image(label="Upload Patient Profile Image", type="pil")
197
+ name = gr.Textbox(label="Name")
198
+ height = gr.Number(label="Height (cm)")
199
+ weight = gr.Number(label="Weight (kg)")
200
+ age = gr.Number(label="Age")
201
+ gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
202
+ residence = gr.Textbox(label="Residence")
203
+ birth_place = gr.Textbox(label="Birth Place")
204
+ occupation = gr.Textbox(label="Occupation")
205
+ medical_history = gr.Textbox(label="Medical History")
206
+ patient_info = gr.State()
207
+ patient_info_submit = gr.Button("Next")
208
+
209
+ # صفحه دوم - انتخاب مدل‌ها و آپلود تصاویر ماموگرافی
210
+ with gr.Tab("Model & Image Selection"):
211
+ model_choice = gr.CheckboxGroup(["how dense is", "what kind is"], label="Select Model(s)", interactive=True)
212
+ mammography_images = gr.File(label="Upload Mammography Image(s)", file_count="multiple", type="filepath")
213
+ predictions = gr.State()
214
+ process_button = gr.Button("Process Images")
215
+
216
+ # صفحه سوم - نمایش اطلاعات و پیش‌بینی
217
+ with gr.Tab("Results"):
218
+ report_display = gr.HTML(label="Patient Report")
219
+ download_button = gr.Button("Download Report")
220
+
221
+ # جمع‌آوری اطلاعات بیمار و انتقال به مرحله بعدی
222
+ def collect_patient_info(image, name, height, weight, age, gender, residence, birth_place, occupation, medical_history):
223
+ # ذخیره تصویر بیمار و اضافه کردن مسیر به اطلاعات بیمار
224
+ image_path = "patient_image.jpg"
225
+ image.save(image_path)
226
+ return {
227
+ "Name": name,
228
+ "Gender": gender,
229
+ "Height": height,
230
+ "Weight": weight,
231
+ "Age": age,
232
+ "Residence": residence,
233
+ "Birth Place": birth_place,
234
+ "Occupation": occupation,
235
+ "Medical History": medical_history,
236
+ "ImagePath": image_path # اضافه کردن مسیر تصویر
237
+ }
238
+
239
+ patient_info_submit.click(
240
+ collect_patient_info,
241
+ inputs=[patient_image, name, height, weight, age, gender, residence, birth_place, occupation, medical_history],
242
+ outputs=patient_info
243
+ )
244
+
245
+ # پردازش تصاویر ماموگرافی با مدل‌های انتخابی
246
+ def process_images(patient_info, selected_models, images):
247
+ all_predictions = []
248
+ for image_file in images:
249
+ image = Image.open(image_file)
250
+ image_predictions = {model: predict_demo(image, model) for model in selected_models}
251
+ all_predictions.append((image_file, image_predictions))
252
+ return all_predictions
253
+
254
+ process_button.click(
255
+ process_images,
256
+ inputs=[patient_info, model_choice, mammography_images],
257
+ outputs=predictions
258
+ )
259
+
260
+ # نمایش گزارش بیمار و پیش‌بینی‌ها در صفحه سوم
261
+ download_button.click(
262
+ display_report,
263
+ inputs=[patient_info, predictions],
264
+ outputs=[report_display, gr.File(label="Download PDF Report")] # اصلاح خروجی برای Gradio
265
+ )
266
+
267
+ demo.launch(debug=True, share=True)
breast_cancer_project_finally_finished.ipynb ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 7,
6
+ "metadata": {
7
+ "id": "GZR221V_EwiN"
8
+ },
9
+ "outputs": [],
10
+ "source": [
11
+ "import pdfkit\n",
12
+ "path_wkhtmltopdf = \"/usr/bin/wkhtmltopdf\"\n",
13
+ "config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)"
14
+ ]
15
+ },
16
+ {
17
+ "cell_type": "code",
18
+ "execution_count": 9,
19
+ "metadata": {
20
+ "id": "e6si8Vop4FjB"
21
+ },
22
+ "outputs": [],
23
+ "source": [
24
+ "# import tensorflow as tf\n",
25
+ "import numpy as np\n",
26
+ "from PIL import Image\n",
27
+ "import cv2\n",
28
+ "import gradio as gr\n",
29
+ "# from numpy import asarray\n",
30
+ "from transformers import pipeline"
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "execution_count": null,
36
+ "metadata": {
37
+ "colab": {
38
+ "base_uri": "https://localhost:8080/"
39
+ },
40
+ "id": "3b-TCKUozaMn",
41
+ "outputId": "58f44bd4-8916-436d-e00a-1e19a4586dbc"
42
+ },
43
+ "outputs": [
44
+ {
45
+ "name": "stdout",
46
+ "output_type": "stream",
47
+ "text": [
48
+ "Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/densenet/densenet201_weights_tf_dim_ordering_tf_kernels_notop.h5\n",
49
+ "74836368/74836368 [==============================] - 4s 0us/step\n"
50
+ ]
51
+ },
52
+ {
53
+ "name": "stderr",
54
+ "output_type": "stream",
55
+ "text": [
56
+ "/usr/local/lib/python3.10/dist-packages/keras/src/engine/training.py:3103: UserWarning: You are saving your model as an HDF5 file via `model.save()`. This file format is considered legacy. We recommend using instead the native Keras format, e.g. `model.save('my_model.keras')`.\n",
57
+ " saving_api.save_model(\n",
58
+ "WARNING:tensorflow:Compiled the loaded model, but the compiled metrics have yet to be built. `model.compile_metrics` will be empty until you train or evaluate the model.\n"
59
+ ]
60
+ }
61
+ ],
62
+ "source": [
63
+ "from tensorflow.keras.layers import Dense, Flatten, GlobalAveragePooling2D, BatchNormalization, Dropout,AveragePooling2D\n",
64
+ "import tensorflow as tf\n",
65
+ "from tensorflow.keras.applications import DenseNet201\n",
66
+ "from keras.models import Model\n",
67
+ "from keras.models import Sequential\n",
68
+ "from keras.regularizers import *\n",
69
+ "from tensorflow import keras\n",
70
+ "from tensorflow.keras import layers"
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "execution_count": 5,
76
+ "metadata": {
77
+ "colab": {
78
+ "base_uri": "https://localhost:8080/",
79
+ "height": 889
80
+ },
81
+ "id": "Ylgxw-pHiLCC",
82
+ "outputId": "76d5f8ed-82f4-4227-ff75-dcbba696eb14"
83
+ },
84
+ "outputs": [
85
+ {
86
+ "name": "stdout",
87
+ "output_type": "stream",
88
+ "text": [
89
+ "Colab notebook detected. This cell will run indefinitely so that you can see errors and logs. To turn off, set debug=False in launch().\n",
90
+ "* Running on public URL: https://54b3e1140167dae729.gradio.live\n",
91
+ "\n",
92
+ "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n"
93
+ ]
94
+ },
95
+ {
96
+ "data": {
97
+ "text/html": [
98
+ "<div><iframe src=\"https://54b3e1140167dae729.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
99
+ ],
100
+ "text/plain": [
101
+ "<IPython.core.display.HTML object>"
102
+ ]
103
+ },
104
+ "metadata": {},
105
+ "output_type": "display_data"
106
+ },
107
+ {
108
+ "name": "stderr",
109
+ "output_type": "stream",
110
+ "text": [
111
+ "WARNING:tensorflow:5 out of the last 5 calls to <function Model.make_predict_function.<locals>.predict_function at 0x78c970190a60> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n"
112
+ ]
113
+ },
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "1/1 [==============================] - 4s 4s/step\n"
119
+ ]
120
+ },
121
+ {
122
+ "name": "stderr",
123
+ "output_type": "stream",
124
+ "text": [
125
+ "WARNING:tensorflow:6 out of the last 6 calls to <function Model.make_predict_function.<locals>.predict_function at 0x78c97cd316c0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n"
126
+ ]
127
+ },
128
+ {
129
+ "name": "stdout",
130
+ "output_type": "stream",
131
+ "text": [
132
+ "1/1 [==============================] - 4s 4s/step\n",
133
+ "1/1 [==============================] - 4s 4s/step\n",
134
+ "1/1 [==============================] - 3s 3s/step\n",
135
+ "1/1 [==============================] - 5s 5s/step\n",
136
+ "1/1 [==============================] - 4s 4s/step\n",
137
+ "1/1 [==============================] - 5s 5s/step\n",
138
+ "1/1 [==============================] - 3s 3s/step\n",
139
+ "1/1 [==============================] - 3s 3s/step\n",
140
+ "1/1 [==============================] - 4s 4s/step\n",
141
+ "1/1 [==============================] - 3s 3s/step\n",
142
+ "1/1 [==============================] - 3s 3s/step\n",
143
+ "Keyboard interruption in main thread... closing server.\n",
144
+ "Killing tunnel 127.0.0.1:7860 <> https://54b3e1140167dae729.gradio.live\n"
145
+ ]
146
+ },
147
+ {
148
+ "data": {
149
+ "text/plain": []
150
+ },
151
+ "execution_count": 5,
152
+ "metadata": {},
153
+ "output_type": "execute_result"
154
+ }
155
+ ],
156
+ "source": [
157
+ "import tensorflow as tf\n",
158
+ "import matplotlib.pyplot as plt\n",
159
+ "import numpy as np\n",
160
+ "from PIL import Image\n",
161
+ "import cv2\n",
162
+ "import gradio as gr\n",
163
+ "from transformers import pipeline\n",
164
+ "import pdfkit # نیاز به نصب دارد (pip install pdfkit)\n",
165
+ "import os\n",
166
+ "\n",
167
+ "# تابع پیش‌بینی\n",
168
+ "def predict_demo(image, model_name):\n",
169
+ " if model_name == \"how dense is\":\n",
170
+ " image = np.asarray(image)\n",
171
+ "\n",
172
+ " # مدل اول\n",
173
+ " def load_model():\n",
174
+ " model = tf.keras.models.load_model(\"/content/model.h5\", compile=False)\n",
175
+ " model.compile(optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=0.00001, decay=0.0001),\n",
176
+ " metrics=[\"accuracy\"], loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.1))\n",
177
+ " model.load_weights(\"/content/modeldense1.h5\")\n",
178
+ " return model\n",
179
+ "\n",
180
+ " model = load_model()\n",
181
+ "\n",
182
+ " def preprocess(image):\n",
183
+ " image = cv2.resize(image, (224, 224))\n",
184
+ " kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])\n",
185
+ " im = cv2.filter2D(image, -1, kernel)\n",
186
+ " if im.ndim == 3:\n",
187
+ " # اضافه کردن بعد جدید برای ورودی مدل\n",
188
+ " im = np.expand_dims(im, axis=0)\n",
189
+ " elif im.ndim == 2:\n",
190
+ " # اگر تصویر سیاه و سفید باشد\n",
191
+ " im = np.expand_dims(im, axis=-1)\n",
192
+ " im = np.repeat(im, 3, axis=-1)\n",
193
+ " im = np.expand_dims(im, axis=0)\n",
194
+ " return im\n",
195
+ "\n",
196
+ "\n",
197
+ " class_name = ['Benign with Density=1', 'Malignant with Density=1', 'Benign with Density=2',\n",
198
+ " 'Malignant with Density=2', 'Benign with Density=3', 'Malignant with Density=3',\n",
199
+ " 'Benign with Density=4', 'Malignant with Density=4']\n",
200
+ "\n",
201
+ " def predict_img(img):\n",
202
+ " img = preprocess(img)\n",
203
+ " img = img / 255.0\n",
204
+ " pred = model.predict(img)[0]\n",
205
+ " return {class_name[i]: float(pred[i]) for i in range(8)}\n",
206
+ "\n",
207
+ "\n",
208
+ " predict_mamo= predict_img(image)\n",
209
+ " return predict_mamo\n",
210
+ "\n",
211
+ " elif model_name == \"what kind is\":\n",
212
+ " image = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)\n",
213
+ " im_pil = Image.fromarray(image)\n",
214
+ " pipe = pipeline(\"image-classification\", model=\"DHEIVER/finetuned-BreastCancer-Classification\", device=0)\n",
215
+ "\n",
216
+ " def predict(image):\n",
217
+ " result = pipe(image)\n",
218
+ " return {result[i]['label']: float(result[i]['score']) for i in range(2)}\n",
219
+ "\n",
220
+ " return predict(im_pil)\n",
221
+ "\n",
222
+ "\n",
223
+ "\n",
224
+ "def generate_fixed_size_chart(predictions, image_file, chart_width=6, chart_height=5):\n",
225
+ " # بارگذاری تصویر ماموگرافی\n",
226
+ " mammo_image = plt.imread(image_file)\n",
227
+ "\n",
228
+ " # تعداد مدل‌ها\n",
229
+ " num_models = len(predictions)\n",
230
+ "\n",
231
+ " # ایجاد figure با تنظیم عرض و ارتفاع هر زیرنمودار\n",
232
+ " fig, axes = plt.subplots(1, num_models + 1, figsize=(chart_width * (num_models + 1), chart_height), constrained_layout=True)\n",
233
+ " # fig.subplots_adjust(wspace=0.7) # فا��له ثابت بین نمودارها\n",
234
+ "\n",
235
+ " # نمایش تصویر ماموگرافی در subplot اول\n",
236
+ " axes[0].imshow(mammo_image, cmap='gray')\n",
237
+ " axes[0].axis('off')\n",
238
+ " axes[0].set_title(\"Mammogram\")\n",
239
+ "\n",
240
+ " # ایجاد نمودارهای پیش‌بینی برای هر مدل در subplots بعدی\n",
241
+ " for i, (model_name, prediction) in enumerate(predictions.items(), start=1):\n",
242
+ " labels, values = zip(*prediction.items())\n",
243
+ " axes[i].barh(labels, values, color='skyblue')\n",
244
+ " axes[i].set_xlabel('Probability (%)')\n",
245
+ " axes[i].set_title(f'{model_name}')\n",
246
+ "\n",
247
+ " # ذخیره‌ی نمودار در فایل\n",
248
+ " chart_path = f\"/content/{os.path.basename(image_file)}_combined_chart.png\"\n",
249
+ " plt.savefig(chart_path, bbox_inches='tight')\n",
250
+ " plt.close(fig)\n",
251
+ "\n",
252
+ " return chart_path\n",
253
+ "\n",
254
+ "def generate_pdf(patient_info, predictions):\n",
255
+ " all_charts = []\n",
256
+ " for image_file, prediction in predictions:\n",
257
+ " chart = generate_fixed_size_chart(prediction, image_file)\n",
258
+ " all_charts.append(chart)\n",
259
+ "\n",
260
+ " # تولید محتوای HTML برای PDF\n",
261
+ " html_content = f\"\"\"\n",
262
+ " <html>\n",
263
+ " <head>\n",
264
+ " <style>\n",
265
+ " body {{ font-family: Arial, sans-serif; }}\n",
266
+ " h1 {{ color: #2F4F4F; text-align: center; margin-bottom: 30px; }}\n",
267
+ " .info-container {{\n",
268
+ " display: flex;\n",
269
+ " flex-wrap: wrap;\n",
270
+ " justify-content: space-between;\n",
271
+ " margin-bottom: 20px;\n",
272
+ " }}\n",
273
+ " .info-item {{\n",
274
+ " width: 45%;\n",
275
+ " margin-bottom: 10px;\n",
276
+ " }}\n",
277
+ " .image-container {{\n",
278
+ " text-align: center;\n",
279
+ " margin-bottom: 50px;\n",
280
+ " }}\n",
281
+ " </style>\n",
282
+ " </head>\n",
283
+ " <body>\n",
284
+ " <h1>Patient Report</h1>\n",
285
+ " <div class=\"image-container\">\n",
286
+ " <h3>Patient Image:</h3>\n",
287
+ " <img src=\"{patient_info.get('ImagePath', '')}\" alt=\"Patient Image\" width=\"300\">\n",
288
+ " </div>\n",
289
+ " <div class=\"image-container\">\n",
290
+ " <h3>Patient Information:</h3>\n",
291
+ " <div class=\"info-container\">\n",
292
+ " {\"\".join(f\"<div class='info-item'><strong>{key}:</strong> {value if value else '-'}</div>\" for key, value in patient_info.items() if key != \"ImagePath\")}\n",
293
+ " </div>\n",
294
+ " </div>\n",
295
+ " <h3>Predictions:</h3>\n",
296
+ " {\"\".join(f\"<div ><img src='{chart}' width='80%'></div>\" for chart in all_charts)}\n",
297
+ " </body>\n",
298
+ " </html>\n",
299
+ " \"\"\"\n",
300
+ "\n",
301
+ " # تنظیمات PDF\n",
302
+ " pdf_path = \"/content/patient_report.pdf\"\n",
303
+ " config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltopdf')\n",
304
+ " options = {\n",
305
+ " \"enable-local-file-access\": True,\n",
306
+ " \"no-stop-slow-scripts\": True,\n",
307
+ " }\n",
308
+ " pdfkit.from_string(html_content, pdf_path, configuration=config, options=options)\n",
309
+ "\n",
310
+ " return pdf_path\n",
311
+ "\n",
312
+ "\n",
313
+ "\n",
314
+ "# تابع نمایش گزارش و تولید PDF\n",
315
+ "def display_report(patient_info, predictions):\n",
316
+ " pdf_path = generate_pdf(patient_info, predictions)\n",
317
+ " report_content = f\"<h2>Patient Report</h2><p>{patient_info}</p><h2>Predictions</h2>{predictions}\"\n",
318
+ " return report_content, pdf_path\n",
319
+ "\n",
320
+ "# رابط Gradio\n",
321
+ "with gr.Blocks() as demo:\n",
322
+ " gr.Markdown(\"## Breast Cancer Detection - Multi-Model Interface\")\n",
323
+ "\n",
324
+ " # صفحه اول - اطلاعات بیمار\n",
325
+ " with gr.Tab(\"Patient Info\"):\n",
326
+ " patient_image = gr.Image(label=\"Upload Patient Profile Image\", type=\"pil\")\n",
327
+ " name = gr.Textbox(label=\"Name\")\n",
328
+ " height = gr.Number(label=\"Height (cm)\")\n",
329
+ " weight = gr.Number(label=\"Weight (kg)\")\n",
330
+ " age = gr.Number(label=\"Age\")\n",
331
+ " gender = gr.Radio([\"Male\", \"Female\", \"Other\"], label=\"Gender\")\n",
332
+ " residence = gr.Textbox(label=\"Residence\")\n",
333
+ " birth_place = gr.Textbox(label=\"Birth Place\")\n",
334
+ " occupation = gr.Textbox(label=\"Occupation\")\n",
335
+ " medical_history = gr.Textbox(label=\"Medical History\")\n",
336
+ " patient_info = gr.State()\n",
337
+ " patient_info_submit = gr.Button(\"Next\")\n",
338
+ "\n",
339
+ " # صفحه دوم - انتخاب مدل‌ها و آپلود تصاویر ماموگرافی\n",
340
+ " with gr.Tab(\"Model & Image Selection\"):\n",
341
+ " model_choice = gr.CheckboxGroup([\"how dense is\", \"what kind is\"], label=\"Select Model(s)\", interactive=True)\n",
342
+ " mammography_images = gr.File(label=\"Upload Mammography Image(s)\", file_count=\"multiple\", type=\"filepath\")\n",
343
+ " predictions = gr.State()\n",
344
+ " process_button = gr.Button(\"Process Images\")\n",
345
+ "\n",
346
+ " # صفحه سوم - نمایش اطلاعات و پیش‌بینی\n",
347
+ " with gr.Tab(\"Results\"):\n",
348
+ " report_display = gr.HTML(label=\"Patient Report\")\n",
349
+ " download_button = gr.Button(\"Download Report\")\n",
350
+ "\n",
351
+ " # جمع‌آوری اطلاعات بیمار و انتقال به مرحله بعدی\n",
352
+ " def collect_patient_info(image, name, height, weight, age, gender, residence, birth_place, occupation, medical_history):\n",
353
+ " # ذخیره تصویر بیمار و اضافه کردن مسیر به اطلاعات بیمار\n",
354
+ " image_path = \"/content/patient_image.jpg\"\n",
355
+ " image.save(image_path)\n",
356
+ " return {\n",
357
+ " \"Name\": name,\n",
358
+ " \"Gender\": gender,\n",
359
+ " \"Height\": height,\n",
360
+ " \"Weight\": weight,\n",
361
+ " \"Age\": age,\n",
362
+ " \"Residence\": residence,\n",
363
+ " \"Birth Place\": birth_place,\n",
364
+ " \"Occupation\": occupation,\n",
365
+ " \"Medical History\": medical_history,\n",
366
+ " \"ImagePath\": image_path # اضافه کردن مسیر تصویر\n",
367
+ " }\n",
368
+ "\n",
369
+ " patient_info_submit.click(\n",
370
+ " collect_patient_info,\n",
371
+ " inputs=[patient_image, name, height, weight, age, gender, residence, birth_place, occupation, medical_history],\n",
372
+ " outputs=patient_info\n",
373
+ " )\n",
374
+ "\n",
375
+ " # پردازش تصاویر ماموگرافی با مدل‌های انتخابی\n",
376
+ " def process_images(patient_info, selected_models, images):\n",
377
+ " all_predictions = []\n",
378
+ " for image_file in images:\n",
379
+ " image = Image.open(image_file)\n",
380
+ " image_predictions = {model: predict_demo(image, model) for model in selected_models}\n",
381
+ " all_predictions.append((image_file, image_predictions))\n",
382
+ " return all_predictions\n",
383
+ "\n",
384
+ " process_button.click(\n",
385
+ " process_images,\n",
386
+ " inputs=[patient_info, model_choice, mammography_images],\n",
387
+ " outputs=predictions\n",
388
+ " )\n",
389
+ "\n",
390
+ " # نمایش گزارش بیمار و پیش‌بینی‌ها در صفحه سوم\n",
391
+ " download_button.click(\n",
392
+ " display_report,\n",
393
+ " inputs=[patient_info, predictions],\n",
394
+ " outputs=[report_display, gr.File(label=\"Download PDF Report\")] # اصلاح خروجی برای Gradio\n",
395
+ " )\n",
396
+ "\n",
397
+ "demo.launch(debug=True, share=True)\n"
398
+ ]
399
+ }
400
+ ],
401
+ "metadata": {
402
+ "accelerator": "GPU",
403
+ "colab": {
404
+ "gpuType": "T4",
405
+ "provenance": []
406
+ },
407
+ "kernelspec": {
408
+ "display_name": "Python 3",
409
+ "name": "python3"
410
+ },
411
+ "language_info": {
412
+ "name": "python"
413
+ }
414
+ },
415
+ "nbformat": 4,
416
+ "nbformat_minor": 0
417
+ }
patient_report.pdf ADDED
Binary file (645 kB). View file
 
requirement.txt CHANGED
@@ -1,11 +1,11 @@
1
- tensorflow==2.15.1
2
- gradio
3
- diffusers
4
- accelerate
5
- git+https://github.com/TencentARC/PhotoMaker.git
6
- pdfkit
7
- wkhtmltopdf
8
- transformers
9
- numpy
10
- pandas
11
  matplotlib
 
1
+ tensorflow==2.15.1
2
+ gradio
3
+ diffusers
4
+ accelerate
5
+ git+https://github.com/TencentARC/PhotoMaker.git
6
+ pdfkit
7
+ wkhtmltopdf
8
+ transformers
9
+ numpy
10
+ pandas
11
  matplotlib
setup.sh CHANGED
@@ -1,2 +1,2 @@
1
- #!/bin/bash
2
  apt-get update && apt-get install -y wkhtmltopdf
 
1
+ #!/bin/bash
2
  apt-get update && apt-get install -y wkhtmltopdf