File size: 11,692 Bytes
a31e3e9
bb0387a
9c30a8b
bb0387a
 
 
 
 
12a6a9f
bb0387a
 
 
 
c46f2d1
bb0387a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d78db55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import os
import subprocess

# دانلود و نصب wkhtmltopdf
def install_wkhtmltopdf():
    try:
        # دانلود فایل deb
        subprocess.run(
            ["wget", "https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6.1-2/wkhtmltox_0.12.6.1-2.bullseye_amd64.deb"],
            check=True
        )
        
        # استخراج فایل‌های deb
        subprocess.run(["ar", "x", "wkhtmltox_0.12.6.1-2.bullseye_amd64.deb"], check=True)
        subprocess.run(["tar", "-xvf", "data.tar.xz"], check=True)
        
        # انتقال فایل‌های اجرایی به دایرکتوری محلی
        os.makedirs("/home/user/bin", exist_ok=True)
        subprocess.run(["cp", "./usr/local/bin/wkhtmltopdf", "/home/user/bin/"], check=True)
        subprocess.run(["cp", "./usr/local/bin/wkhtmltoimage", "/home/user/bin/"], check=True)
        
        # اضافه کردن مسیر به PATH
        os.environ["PATH"] += os.pathsep + "/home/user/bin"
        print("wkhtmltopdf installed successfully.")
        
    except subprocess.CalledProcessError as e:
        print(f"Error during wkhtmltopdf installation: {e}")
        raise

# اجرای نصب در صورت نیاز
if not os.path.exists("/home/user/bin/wkhtmltopdf"):
    install_wkhtmltopdf()

# اکنون می‌توانید از pdfkit استفاده کنید
import pdfkit
# path_wkhtmltopdf = "/usr/bin/wkhtmltopdf"
# config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
import subprocess

try:
    path_wkhtmltopdf = subprocess.check_output(['which', 'wkhtmltopdf']).decode('utf-8').strip()
    config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
except subprocess.CalledProcessError:
    raise FileNotFoundError("wkhtmltopdf not found. Ensure it is installed in your environment.")


# import tensorflow as tf
import numpy as np
from PIL import Image
import cv2
import gradio as gr
# from numpy import asarray
from transformers import pipeline

from tensorflow.keras.layers import Dense, Flatten, GlobalAveragePooling2D, BatchNormalization, Dropout,AveragePooling2D
import tensorflow as tf
from tensorflow.keras.applications import DenseNet201
from keras.models import Model
from keras.models import Sequential
from keras.regularizers import *
from tensorflow import keras
from tensorflow.keras import layers

import tensorflow as tf
import matplotlib.pyplot as plt
from PIL import Image
import cv2
from transformers import pipeline

# تابع پیش‌بینی
def predict_demo(image, model_name):
    if model_name == "how dense is":
        image = np.asarray(image)

        # مدل اول
        def load_model():
            model = tf.keras.models.load_model("model.h5", compile=False)
            model.compile(optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=0.00001, decay=0.0001),
                          metrics=["accuracy"], loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.1))
            model.load_weights("modeldense1.h5")
            return model

        model = load_model()

        def preprocess(image):
            image = cv2.resize(image, (224, 224))
            kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
            im = cv2.filter2D(image, -1, kernel)
            if im.ndim == 3:
                # اضافه کردن بعد جدید برای ورودی مدل
                im = np.expand_dims(im, axis=0)
            elif im.ndim == 2:
                # اگر تصویر سیاه و سفید باشد
                im = np.expand_dims(im, axis=-1)
                im = np.repeat(im, 3, axis=-1)
                im = np.expand_dims(im, axis=0)
            return im


        class_name = ['Benign with Density=1', 'Malignant with Density=1', 'Benign with Density=2',
                      'Malignant with Density=2', 'Benign with Density=3', 'Malignant with Density=3',
                      'Benign with Density=4', 'Malignant with Density=4']

        def predict_img(img):
            img = preprocess(img)
            img = img / 255.0
            pred = model.predict(img)[0]
            return {class_name[i]: float(pred[i]) for i in range(8)}


        predict_mamo= predict_img(image)
        return predict_mamo

    elif model_name == "what kind is":
        image = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)
        im_pil = Image.fromarray(image)
        pipe = pipeline("image-classification", model="DHEIVER/finetuned-BreastCancer-Classification", device=0)

        def predict(image):
            result = pipe(image)
            return {result[i]['label']: float(result[i]['score']) for i in range(2)}

        return predict(im_pil)



def generate_fixed_size_chart(predictions, image_file, chart_width=6, chart_height=5):
    # بارگذاری تصویر ماموگرافی
    mammo_image = plt.imread(image_file)

    # تعداد مدل‌ها
    num_models = len(predictions)

    # ایجاد figure با تنظیم عرض و ارتفاع هر زیرنمودار
    fig, axes = plt.subplots(1, num_models + 1, figsize=(chart_width * (num_models + 1), chart_height), constrained_layout=True)
    # fig.subplots_adjust(wspace=0.7)  # فاصله ثابت بین نمودارها

    # نمایش تصویر ماموگرافی در subplot اول
    axes[0].imshow(mammo_image, cmap='gray')
    axes[0].axis('off')
    axes[0].set_title("Mammogram")

    # ایجاد نمودارهای پیش‌بینی برای هر مدل در subplots بعدی
    for i, (model_name, prediction) in enumerate(predictions.items(), start=1):
        labels, values = zip(*prediction.items())
        axes[i].barh(labels, values, color='skyblue')
        axes[i].set_xlabel('Probability (%)')
        axes[i].set_title(f'{model_name}')

    # ذخیره‌ی نمودار در فایل
    chart_path = f"{os.getcwd()}/{os.path.basename(image_file)}_combined_chart.png"
    plt.savefig(chart_path, bbox_inches='tight')
    plt.close(fig)

    return chart_path

def generate_pdf(patient_info, predictions):
    all_charts = []
    for image_file, prediction in predictions:
        chart = generate_fixed_size_chart(prediction, image_file)
        all_charts.append(chart)

    # تولید محتوای HTML برای PDF
    html_content = f"""
    <html>
    <head>
        <style>
            body {{ font-family: Arial, sans-serif; }}
            h1 {{ color: #2F4F4F; text-align: center; margin-bottom: 30px; }}
            .info-container {{
                display: flex;
                flex-wrap: wrap;
                justify-content: space-between;
                margin-bottom: 20px;
            }}
            .info-item {{
                width: 45%;
                margin-bottom: 10px;
            }}
            .image-container {{
                text-align: center;
                margin-bottom: 50px;
            }}
        </style>
    </head>
    <body>
        <h1>Patient Report</h1>
        <div class="image-container">
            <h3>Patient Image:</h3>
            <img src="{patient_info.get('ImagePath', '')}" alt="Patient Image" width="300">
        </div>
        <div class="image-container">
            <h3>Patient Information:</h3>
            <div class="info-container">
                {"".join(f"<div class='info-item'><strong>{key}:</strong> {value if value else '-'}</div>" for key, value in patient_info.items() if key != "ImagePath")}
            </div>
        </div>
        <h3>Predictions:</h3>
        {"".join(f"<div ><img src='{chart}' width='80%'></div>" for chart in all_charts)}
    </body>
    </html>
    """

    # تنظیمات PDF
    pdf_path = "patient_report.pdf"
    config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltopdf')
    options = {
        "enable-local-file-access": True,
        "no-stop-slow-scripts": True,
    }
    pdfkit.from_string(html_content, pdf_path, configuration=config, options=options)

    return pdf_path



# تابع نمایش گزارش و تولید PDF
def display_report(patient_info, predictions):
    pdf_path = generate_pdf(patient_info, predictions)
    report_content = f"<h2>Patient Report</h2><p>{patient_info}</p><h2>Predictions</h2>{predictions}"
    return report_content, pdf_path

# رابط Gradio
with gr.Blocks() as demo:
    gr.Markdown("## Breast Cancer Detection - Multi-Model Interface")

    # صفحه اول - اطلاعات بیمار
    with gr.Tab("Patient Info"):
        patient_image = gr.Image(label="Upload Patient Profile Image", type="pil")
        name = gr.Textbox(label="Name")
        height = gr.Number(label="Height (cm)")
        weight = gr.Number(label="Weight (kg)")
        age = gr.Number(label="Age")
        gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
        residence = gr.Textbox(label="Residence")
        birth_place = gr.Textbox(label="Birth Place")
        occupation = gr.Textbox(label="Occupation")
        medical_history = gr.Textbox(label="Medical History")
        patient_info = gr.State()
        patient_info_submit = gr.Button("Next")

    # صفحه دوم - انتخاب مدل‌ها و آپلود تصاویر ماموگرافی
    with gr.Tab("Model & Image Selection"):
        model_choice = gr.CheckboxGroup(["how dense is", "what kind is"], label="Select Model(s)", interactive=True)
        mammography_images = gr.File(label="Upload Mammography Image(s)", file_count="multiple", type="filepath")
        predictions = gr.State()
        process_button = gr.Button("Process Images")

    # صفحه سوم - نمایش اطلاعات و پیش‌بینی
    with gr.Tab("Results"):
        report_display = gr.HTML(label="Patient Report")
        download_button = gr.Button("Download Report")

    # جمع‌آوری اطلاعات بیمار و انتقال به مرحله بعدی
    def collect_patient_info(image, name, height, weight, age, gender, residence, birth_place, occupation, medical_history):
        # ذخیره تصویر بیمار و اضافه کردن مسیر به اطلاعات بیمار
        image_path = "patient_image.jpg"
        image.save(image_path)
        return {
            "Name": name,
            "Gender": gender,
            "Height": height,
            "Weight": weight,
            "Age": age,
            "Residence": residence,
            "Birth Place": birth_place,
            "Occupation": occupation,
            "Medical History": medical_history,
            "ImagePath": image_path  # اضافه کردن مسیر تصویر
        }

    patient_info_submit.click(
        collect_patient_info,
        inputs=[patient_image, name, height, weight, age, gender, residence, birth_place, occupation, medical_history],
        outputs=patient_info
    )

    # پردازش تصاویر ماموگرافی با مدل‌های انتخابی
    def process_images(patient_info, selected_models, images):
        all_predictions = []
        for image_file in images:
            image = Image.open(image_file)
            image_predictions = {model: predict_demo(image, model) for model in selected_models}
            all_predictions.append((image_file, image_predictions))
        return all_predictions

    process_button.click(
        process_images,
        inputs=[patient_info, model_choice, mammography_images],
        outputs=predictions
    )

    # نمایش گزارش بیمار و پیش‌بینی‌ها در صفحه سوم
    download_button.click(
        display_report,
        inputs=[patient_info, predictions],
        outputs=[report_display, gr.File(label="Download PDF Report")]  # اصلاح خروجی برای Gradio
    )

demo.launch(debug=True, share=True)