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"""
{patient_info}