dangtiendatdat commited on
Commit
df88d2c
·
verified ·
1 Parent(s): c1ab5f9

Upload 9 files

Browse files
Files changed (9) hide show
  1. BrainTumor.py +39 -0
  2. ChatBot.py +61 -0
  3. Detectskindisease.py +144 -0
  4. Pneumonia.py +35 -0
  5. Polyb.py +54 -0
  6. brainbbox.png +0 -0
  7. braintt.jpg +0 -0
  8. thuydau.jpg +0 -0
  9. viemphoi.jpeg +0 -0
BrainTumor.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image, ImageDraw
2
+ from transformers import pipeline
3
+ import datasets
4
+ import gradio as gr
5
+ import os
6
+ from datasets import load_dataset
7
+
8
+ data = load_dataset("Francesco/brain-tumor-m2pbp")
9
+ pipe = pipeline("object-detection", model="DunnBC22/yolos-tiny-Brain_Tumor_Detection")
10
+
11
+ def Processing(Image):
12
+
13
+ data = pipe(Image)
14
+
15
+ for Num_of_Label in range(len(data)) :
16
+
17
+ Color_List = ["purple", "yellow", "blue"]
18
+
19
+ box = data[Num_of_Label]['box']
20
+
21
+ xmin, ymin, xmax, ymax = box['xmin'], box['ymin'], box['xmax'], box['ymax']
22
+
23
+ draw = ImageDraw.Draw(Image)
24
+
25
+ draw.rectangle([xmin, ymin, xmax, ymax], outline= Color_List[Num_of_Label], width=2)
26
+
27
+ return Image
28
+ def create_brain_tumor_detect() :
29
+ with gr.Blocks() as Brain_Tumor_Detect:
30
+ gr.Markdown("Hãy tải ảnh lên và nhấn **Xử Lý** để khoanh vùng u não.")
31
+ with gr.Row():
32
+
33
+
34
+ inp = gr.Image(label = "Xin Nhập Ảnh Vào", type = 'pil', height=512, width=512,
35
+ value=os.path.join(os.path.dirname(__file__), "../Image/braintt.jpg"),interactive=True)
36
+ out = gr.Image(label = "Kết Quả", type = 'pil')
37
+ btn = gr.Button("Xử Lý")
38
+ btn.click(fn=Processing, inputs= inp, outputs=out)
39
+ return Brain_Tumor_Detect
ChatBot.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import gradio as gr
3
+ key = "f914daada5mshde035a916247607p148638jsn0abe47d56130"
4
+
5
+ system_message = '''Bạn là một trợ lý tư vấn chăm sóc sức khỏe tên là Dr.Hera.
6
+ Hãy hỏi rõ về triệu chứng khi người dùng gặp một vấn đề nào đó,
7
+ hãy cung cấp thông tin hoặc lời khuyên khi người dùng nói về một căn bệnh nào đó.
8
+ Lưu ý người dùng của bạn là một người Việt Nam không có kiến thức về y tế,
9
+ do đó bạn phải cung cấp các lời khuyên chính xác, ngắn gọn, đầy đủ đối với các câu hỏi liên quan đến sức khỏe.
10
+ Trả lời rằng bạn không thể hỗ trợ các vấn đề không liên quan đến sức khỏe khi nhận các câu hỏi không liên quan đến sức khỏe.
11
+ Chỉ được trả lời bằng Tiếng Việt.
12
+ Hãy làm câu trả lời hoàn chỉnh về mặt nội dung và cấu trúc.'''
13
+
14
+ def chatbotfnc(message, history):
15
+ url = "https://chatgpt-42.p.rapidapi.com/gpt4"
16
+ # Thêm tin nhắn của người dùng vào lịch sử hội thoại
17
+
18
+ conversation_history = [ ]
19
+ for human, assistant in history:
20
+ conversation_history.append({"role": "user", "content": human })
21
+ conversation_history.append({"role": "assistant", "content":assistant})
22
+ conversation_history.append({"role": "user", "content": message})
23
+
24
+
25
+ payload = {
26
+ "messages": conversation_history,
27
+ "system_prompt": system_message,
28
+ "temperature": 0.5, # Tăng độ sáng tạo để phản hồi tự nhiên hơn
29
+ "top_k": 40, # Giảm top_k để tăng tính ổn định trong câu trả lời
30
+ "top_p": 0.85, # Giảm top_p để câu trả lời tập trung hơn
31
+ "max_tokens": 1000, # Giới hạn số từ để tránh phản hồi dài quá mức
32
+ "web_access": False
33
+ }
34
+
35
+
36
+ headers = {
37
+ "x-rapidapi-key": key,
38
+ "x-rapidapi-host": "chatgpt-42.p.rapidapi.com",
39
+ "Content-Type": "application/json"
40
+ }
41
+
42
+ try:
43
+ response = requests.post(url, json=payload, headers=headers)
44
+ # response.raise_for_status() # Kiểm tra lỗi HTTP
45
+ result = response.json()
46
+
47
+ # Kiểm tra xem phản hồi có chứa khóa 'result' hay không
48
+ if 'result' in result:
49
+ hera_response = result['result']
50
+ return hera_response
51
+ else:
52
+ return result['error']
53
+
54
+ except requests.exceptions.RequestException as e :
55
+ return f"Lỗi kết nối hoặc HTTP: {e} "
56
+
57
+ def create_Chatbot_tab(chatkey="Fix bug key"):
58
+
59
+ Chatbot_tab = gr.ChatInterface(fn=chatbotfnc, examples=["Tôi bị đau dạ dày mạn tính vừa rồi tôi ăn xoài chua,tôi nên làm gì đây?", "Tôi khó thở vì covid tôi nên làm gì đây", "Tôi bị đau dạ dày lâu năm"], title="Bs.Hera", description = "Trợ lý ảo - tư vấn sức khỏe", theme = "soft", submit_btn = "Gửi",
60
+ stop_btn = "Tạm dừng")
61
+ return Chatbot_tab
Detectskindisease.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import gradio as gr
3
+ from PIL import Image
4
+ import io
5
+ import numpy as np
6
+ import os
7
+ key = "2cff2aab49msh5191ef59693cc02p1091a7jsnd7100bb29621"
8
+ trans_disease = {
9
+ "acne": "mụn",
10
+ "actinic_keratosis": "chứng dày sừng quang hóa",
11
+ "alopecia_androgenetica": "chứng rụng tóc nội tiết tố androgen",
12
+ "alopecia_areata": "chứng rụng tóc từng vùng",
13
+ "bullous_dermatosis": "bệnh da bọng nước",
14
+ "chloasma": "nám da",
15
+ "corn": "chứng chai da",
16
+ "dermatofibroma": "u xơ da",
17
+ "eczema_dermatitis": "viêm da chàm",
18
+ "erysipelas": "viêm quầng",
19
+ "erythema_multiforme": "ban đỏ đa dạng",
20
+ "folliculitis": "viêm nang lông",
21
+ "furuncle": "mụn nhọt",
22
+ "haemangioma": "bệnh u máu",
23
+ "herpes": "mụn rộp",
24
+ "herpes_simplex": "nhiễm trùng do virus Herpes Simplex",
25
+ "iga_vasculitis": "viêm mạch máu Iga",
26
+ "keloid": "sẹo lồi",
27
+ "keratosis_follicularism": "bệnh nang lông dày sừng",
28
+ "lichen_planus": "bệnh lichen phẳng",
29
+ "lupus_erythematosus": "bệnh ban đỏ",
30
+ "molluscum_contagiosum": "u mềm lây",
31
+ "nevus": "nốt ruồi",
32
+ "paronychia": "viêm quanh móng",
33
+ "pityriasis_alba": "bệnh vẩy phấn trắng",
34
+ "pityriasis_rosea": "bệnh vảy phấn hồng",
35
+ "prurigo_nodularis": "bệnh sẩn ngứa",
36
+ "psoriasis": "bệnh vẩy nến",
37
+ "rosacea": "bệnh trứng cá đỏ rosacea",
38
+ "sebaceous_cyst": "u nang bã nhờn",
39
+ "sebaceousnevus": "bớt tuyến bã",
40
+ "seborrheic_dermatitis": "viêm da tiết bã",
41
+ "seborrheic_keratosis": "chứng dày sừng tiết bã",
42
+ "skin_tag": "mụn thịt dư",
43
+ "stasis_dermatitis": "viêm da ứ đọng",
44
+ "syringoma": "u ống tuyến mồ hôi",
45
+ "tinea_capitis": "nấm da đầu",
46
+ "tinea_corporis": "nấm cơ thể",
47
+ "tinea_cruris": "nấm bẹn",
48
+ "tinea_manuum": "",
49
+ "tinea_pedis": "nấm chân",
50
+ "tinea_unguium": "nấm móng tay móng chân",
51
+ "tinea_versicolor": "bệnh lang ben",
52
+ "urticaria": "phát ban",
53
+ "urticaria_papular": "nổi mề đay",
54
+ "varicella": "thủy đậu",
55
+ "verruca_plana": "mụn cóc phẳng",
56
+ "verruca_vulgaris": "mụn cóc thông thường",
57
+ "vitiligo": "bệnh bạch biến"
58
+ }
59
+ trans_body = {
60
+ "head": "đầu",
61
+ "neck": "cổ",
62
+ "hand": "tay",
63
+ "arm": "cánh tay",
64
+ "leg": "chân",
65
+ "foot": "bàn chân",
66
+ "back": "lưng",
67
+ "chest": "ngực",
68
+ "abdomen": "bụng",
69
+ "face": "mặt",
70
+ "ear": "tai",
71
+ "eye": "mắt",
72
+ "nose": "mũi",
73
+ "mouth": "miệng",
74
+ "lip": "môi",
75
+ "cheek": "má",
76
+ "tongue": "lưỡi",
77
+ "throat": "cổ họng",
78
+ "forehead": "trán",
79
+ "chin": "cằm",
80
+ "unknown" : "bộ phận chưa rõ"
81
+ }
82
+ def detect_skin_disease(image,key):
83
+ try:
84
+
85
+ # Convert NumPy array to image file-like object
86
+ img = Image.fromarray((image).astype('uint8'))
87
+ img_byte_array = io.BytesIO()
88
+ img.save(img_byte_array, format='PNG')
89
+ img_byte_array.seek(0)
90
+
91
+ url = "https://detect-skin-disease.p.rapidapi.com/facebody/analysis/detect-skin-disease"
92
+ # files = {"image": img_byte_array}
93
+ files = {"image": ("image.png", img_byte_array, "image/png")}
94
+ headers = {
95
+ "X-RapidAPI-Key": key,
96
+ "X-RapidAPI-Host": "detect-skin-disease.p.rapidapi.com"
97
+ }
98
+ response = requests.post(url, files=files, headers=headers)
99
+ response_json = response.json()
100
+
101
+ output = ""
102
+
103
+ if 'data' in response_json:
104
+ body_part = response_json['data'].get('body_part')
105
+ results = response_json['data'].get('results_english')
106
+
107
+ if body_part is not None:
108
+ vnese_body = trans_body[body_part]
109
+ output += f"Phần của cơ thể: {vnese_body} ({body_part})\n"
110
+
111
+ if results is not None:
112
+ output += " Kết quả phân tích: "
113
+
114
+ # Sort the results by probability percentage in descending order
115
+ sorted_results = sorted(results.items(), key=lambda x: x[1], reverse=True)
116
+
117
+ for disease, probability in sorted_results:
118
+ probability_percent = probability * 100
119
+ vnese_disease = trans_disease.get(disease, disease)
120
+ if probability_percent >= 10:
121
+ output += f"{vnese_disease} : {probability_percent:.2f}%\n"
122
+
123
+ return output
124
+ else:
125
+ return "Không có dữ liệu phản hồi từ API."
126
+ except Exception as e:
127
+ return f"Error: {str(e)}"
128
+
129
+ def create_skin_tab(skinkey="2cff2aab49msh5191ef59693cc02p1091a7jsnd7100bb29621"):
130
+ css = """
131
+ .textboxskin {
132
+ font-sxxxxize: 50px; !important;
133
+ }
134
+ """
135
+ with gr.Blocks(css=css) as demo:
136
+ keybox = gr.Text(value=skinkey,visible=False)
137
+ gr.Markdown("Hãy tải ảnh lên và nhấn **Xử Lý** để chẩn đoán bệnh ngoài da.")
138
+ with gr.Row():
139
+ inp = gr.Image(type="numpy",height=512, width=512,
140
+ value=os.path.join(os.path.dirname(__file__), "../Image/thuydau.jpg"))
141
+ out = gr.Label(label="Kết Quả Dự Đoán",elem_classes="textboxskin")
142
+ btn = gr.Button("Xử Lý")
143
+ btn.click(fn=detect_skin_disease, inputs=[inp,keybox], outputs=out)
144
+ return demo
Pneumonia.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ import os
3
+
4
+ # Load model directly
5
+ from transformers import AutoImageProcessor, AutoModelForImageClassification
6
+ import gradio as gr
7
+ processor = AutoImageProcessor.from_pretrained("nickmuchi/vit-finetuned-chest-xray-pneumonia")
8
+ model = AutoModelForImageClassification.from_pretrained("nickmuchi/vit-finetuned-chest-xray-pneumonia")
9
+ def update(image_processed):
10
+ #image = Image.open(image_url)
11
+ #image_processed = image.convert("RGB")
12
+
13
+ inputs = processor(images=image_processed, return_tensors="pt")
14
+ outputs = model(**inputs)
15
+ logits = outputs.logits
16
+ predicted_class_idx = logits.argmax(-1).item()
17
+
18
+ for class_name, score in zip(model.config.id2label.values(), logits.softmax(dim=-1).squeeze().tolist()):
19
+ ket_qua = "Viêm phổi"
20
+ if (class_name == "NORMAL") :
21
+ ket_qua = "Bình thường"
22
+ if (model.config.id2label[predicted_class_idx] == class_name) :
23
+ return (f"{ket_qua}: {score:.0%}")
24
+ return ""
25
+ def create_pneumonia_tab() :
26
+ with gr.Blocks() as demo:
27
+ gr.Markdown("Hãy tải ảnh lên và nhấn **Xử Lý** để chẩn đoán viêm phổi.")
28
+ with gr.Row():
29
+
30
+
31
+ inp = gr.Image(label= "Nhập Ảnh",type="pil",value=os.path.join(os.path.dirname(__file__), "../Image/viemphoi.jpeg"),interactive=True)
32
+ out = gr.Label(label="Kết Quả Dự Đoán")
33
+ btn = gr.Button("Xử Lý")
34
+ btn.click(fn=update, inputs=inp, outputs=out)
35
+ return demo
Polyb.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ import numpy as np
3
+ import requests
4
+ from PIL import Image
5
+ import gradio as gr
6
+ from lang_sam import LangSAM
7
+ model = LangSAM()
8
+
9
+ text_prompt = """
10
+ A polyp is an anomalous oval-shaped small bump-like structure, a relatively small growth or
11
+ mass that develops on the inner lining of the colon or other organs.
12
+ Multiple polyps may exist in one image.
13
+ """
14
+
15
+ def highlight_mask_on_image(image, mask_np, color=(0, 200, 0), alpha=0.7):
16
+ """Tô màu cho khu vực được xác định bởi mask lên hình ảnh gốc."""
17
+ image_np = np.array(image)
18
+
19
+ if mask_np.shape != image_np.shape[:2]:
20
+ raise ValueError("Kích thước của mask không khớp với kích thước của hình ảnh")
21
+
22
+ highlighted_image = image_np.copy()
23
+
24
+ mask_indices = mask_np > 0 # Chỉ lấy các vùng có mask
25
+ highlighted_image[mask_indices] = (1 - alpha) * image_np[mask_indices] + alpha * np.array(color)
26
+
27
+ return Image.fromarray(highlighted_image.astype(np.uint8))
28
+
29
+ def main(image):
30
+
31
+ image_pil = image.convert("RGB")
32
+ masks, boxes, phrases, logits = model.predict(image_pil, text_prompt)
33
+
34
+ if len(masks) == 1:
35
+ print(f"No objects of the '{text_prompt}' prompt detected in the image.")
36
+ return image_pil # Trả về ảnh gốc nếu không phát hiện ra mask
37
+ masks_np = [mask.squeeze().cpu().numpy() for mask in masks]
38
+
39
+ if len(masks_np) > 1:
40
+ combined_mask = np.sum(masks_np[1:], axis=0) > 0
41
+ else:
42
+ combined_mask = masks_np[0]
43
+ highlighted_image = highlight_mask_on_image(image_pil, combined_mask)
44
+
45
+ return highlighted_image
46
+ def create_polyb():
47
+ demo = gr.Interface(
48
+ fn=main,
49
+ inputs=gr.Image(type="pil"),
50
+ outputs=gr.Image(type="pil"),
51
+ title="Highlight Polyps",
52
+ description="Tải lên một hình ảnh và phát hiện polyp với LangSAM."
53
+ )
54
+ return demo
brainbbox.png ADDED
braintt.jpg ADDED
thuydau.jpg ADDED
viemphoi.jpeg ADDED