mgbam commited on
Commit
8be8858
Β·
verified Β·
1 Parent(s): 21436da

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -72
app.py CHANGED
@@ -1,19 +1,40 @@
1
- import gradio as gr
 
 
2
  import requests
3
 
4
- # Load the Skin Cancer Image Classification model
5
- classifier = gr.load("models/Anwarkh1/Skin_Cancer-Image_Classification")
 
 
 
 
 
 
 
 
6
 
7
- # Functionality: Classify Skin Cancer Image
 
 
 
 
8
  def classify_skin_cancer(image):
9
- results = classifier(image)
10
  label = results[0]['label']
11
  confidence = results[0]['score']
12
  explanation = f"The model predicts **{label}** with a confidence of {confidence:.2%}."
13
  return label, confidence, explanation
14
 
15
- # Functionality: Fetch Latest Cancer Research Papers
 
 
 
16
  def fetch_cancer_research():
 
 
 
 
17
  api_url = "https://api.semanticscholar.org/graph/v1/paper/search"
18
  params = {
19
  "query": "skin cancer research",
@@ -33,75 +54,87 @@ def fetch_cancer_research():
33
  else:
34
  return "Error fetching research papers. Please try again later."
35
 
36
- # Functionality: Provide Patient-Friendly Explanation
37
- def generate_explanation(label, confidence):
38
- if label.lower() == "melanoma":
39
- message = (
40
- f"The prediction is **Melanoma**, with a confidence of **{confidence:.2%}**. "
41
- f"This type of skin cancer is potentially serious and requires immediate medical attention. "
42
- f"Please consult a dermatologist for further evaluation and treatment."
43
- )
44
- elif label.lower() == "benign keratosis-like lesions":
45
- message = (
46
- f"The prediction is **Benign Keratosis-like Lesion**, with a confidence of **{confidence:.2%}**. "
47
- f"This is generally non-cancerous but can sometimes require medical observation. "
48
- f"Consult a healthcare provider for a definitive diagnosis."
49
- )
50
- else:
51
- message = (
52
- f"The prediction is **{label}**, with a confidence of **{confidence:.2%}**. "
53
- f"More detailed evaluation is recommended. Please consult a healthcare professional."
54
- )
55
- return message
56
 
57
- # Gradio Multi-Application System (MAS)
58
- with gr.Blocks() as mas:
59
- gr.Markdown("""
60
- # 🌍 AI-Powered Skin Cancer Detection and Research Assistant 🩺
61
- This multi-functional platform provides skin cancer classification, patient-friendly explanations,
62
- and access to the latest research papers to empower healthcare and save lives.
63
- """)
 
 
 
 
 
 
 
 
64
 
65
- with gr.Tab("πŸ” Skin Cancer Classification"):
66
- with gr.Row():
67
- image = gr.Image(type="pil", label="Upload Skin Image")
68
- classify_button = gr.Button("Classify Image")
69
-
70
- label = gr.Textbox(label="Predicted Label", interactive=False)
71
- confidence = gr.Slider(label="Confidence", interactive=False, minimum=0, maximum=1, step=0.01)
72
- explanation = gr.Textbox(label="Patient-Friendly Explanation", interactive=False)
73
-
74
- classify_button.click(classify_skin_cancer, inputs=image, outputs=[label, confidence, explanation])
75
 
76
- with gr.Tab("πŸ“„ Latest Research Papers"):
77
- with gr.Row():
78
- fetch_button = gr.Button("Fetch Latest Papers")
79
-
80
- research_papers = gr.Markdown()
81
- fetch_button.click(fetch_cancer_research, inputs=[], outputs=research_papers)
82
 
83
- with gr.Tab("πŸ› οΈ Model Information"):
84
- gr.Markdown("""
85
- ## Skin Cancer Image Classification Model
86
- - **Model Architecture:** Vision Transformer (ViT)
87
- - **Trained On:** Skin Cancer Dataset (ISIC)
88
- - **Classes:** Benign keratosis-like lesions, Basal cell carcinoma, Actinic keratoses, Vascular lesions, Melanocytic nevi, Melanoma, Dermatofibroma
89
- - **Performance Metrics:**
90
- - **Validation Accuracy:** 96.95%
91
- - **Train Accuracy:** 96.14%
92
- - **Loss Function:** Cross-Entropy
93
- """)
94
 
95
- with gr.Tab("ℹ️ About This Project"):
96
- gr.Markdown("""
97
- ### About
98
- This project is developed by **[mgbam](https://huggingface.co/mgbam)** to revolutionize cancer detection and research accessibility.
99
- #### Features:
100
- - State-of-the-art AI-powered skin cancer detection.
101
- - Explanations designed for patients and clinicians.
102
- - Access to the latest research insights for global collaboration.
103
- """)
104
- gr.Markdown("🎯 Let's work together to save lives and make healthcare accessible for all.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
- # Launch the MAS
107
- mas.launch()
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from transformers import pipeline
3
+ from PIL import Image
4
  import requests
5
 
6
+ # =======================
7
+ # Caching the Model
8
+ # =======================
9
+ @st.cache_resource
10
+ def load_model():
11
+ """
12
+ Load the pre-trained skin cancer classification model.
13
+ Cached to prevent reloading on every app interaction.
14
+ """
15
+ return pipeline("image-classification", model="Anwarkh1/Skin_Cancer-Image_Classification")
16
 
17
+ model = load_model()
18
+
19
+ # =======================
20
+ # Functionality: Classify Skin Cancer
21
+ # =======================
22
  def classify_skin_cancer(image):
23
+ results = model(image)
24
  label = results[0]['label']
25
  confidence = results[0]['score']
26
  explanation = f"The model predicts **{label}** with a confidence of {confidence:.2%}."
27
  return label, confidence, explanation
28
 
29
+ # =======================
30
+ # Functionality: Fetch Cancer Research Papers
31
+ # =======================
32
+ @st.cache_data
33
  def fetch_cancer_research():
34
+ """
35
+ Fetch the latest research papers related to skin cancer.
36
+ Cached to avoid repeated API calls.
37
+ """
38
  api_url = "https://api.semanticscholar.org/graph/v1/paper/search"
39
  params = {
40
  "query": "skin cancer research",
 
54
  else:
55
  return "Error fetching research papers. Please try again later."
56
 
57
+ # =======================
58
+ # Streamlit Page Config
59
+ # =======================
60
+ st.set_page_config(
61
+ page_title="AI-Powered Skin Cancer Detection",
62
+ page_icon="🩺",
63
+ layout="wide",
64
+ initial_sidebar_state="expanded"
65
+ )
 
 
 
 
 
 
 
 
 
 
 
66
 
67
+ st.sidebar.header("Navigation")
68
+ app_mode = st.sidebar.radio(
69
+ "Choose a feature",
70
+ ["πŸ” Skin Cancer Classification", "πŸ“„ Latest Research Papers", "ℹ️ About the Model"]
71
+ )
72
+
73
+ # =======================
74
+ # Skin Cancer Classification
75
+ # =======================
76
+ if app_mode == "πŸ” Skin Cancer Classification":
77
+ st.title("πŸ” Skin Cancer Classification")
78
+ st.write(
79
+ "Upload an image of the skin lesion, and the AI model will classify it as one of several types, "
80
+ "such as melanoma, basal cell carcinoma, or benign keratosis-like lesions."
81
+ )
82
 
83
+ uploaded_image = st.file_uploader("Upload a skin lesion image", type=["png", "jpg", "jpeg"])
 
 
 
 
 
 
 
 
 
84
 
85
+ if uploaded_image:
86
+ image = Image.open(uploaded_image).convert('RGB')
87
+ st.image(image, caption="Uploaded Image", use_column_width=True)
 
 
 
88
 
89
+ # Perform classification
90
+ st.write("Classifying...")
91
+ label, confidence, explanation = classify_skin_cancer(image)
 
 
 
 
 
 
 
 
92
 
93
+ # Display results
94
+ st.markdown(f"### **Prediction**: {label}")
95
+ st.markdown(f"### **Confidence**: {confidence:.2%}")
96
+ st.markdown(f"### **Explanation**: {explanation}")
97
+
98
+ # =======================
99
+ # Latest Research Papers
100
+ # =======================
101
+ elif app_mode == "πŸ“„ Latest Research Papers":
102
+ st.title("πŸ“„ Latest Research Papers")
103
+ st.write(
104
+ "Fetch the latest research papers on skin cancer to stay updated on recent findings and innovations."
105
+ )
106
+
107
+ if st.button("Fetch Papers"):
108
+ with st.spinner("Fetching research papers..."):
109
+ summaries = fetch_cancer_research()
110
+ st.markdown(summaries)
111
+
112
+ # =======================
113
+ # About the Model
114
+ # =======================
115
+ elif app_mode == "ℹ️ About the Model":
116
+ st.title("ℹ️ About the Skin Cancer Detection Model")
117
+ st.markdown("""
118
+ - **Model Architecture:** Vision Transformer (ViT)
119
+ - **Trained On:** Skin Cancer Dataset (ISIC)
120
+ - **Classes:**
121
+ - Benign keratosis-like lesions
122
+ - Basal cell carcinoma
123
+ - Actinic keratoses
124
+ - Vascular lesions
125
+ - Melanocytic nevi
126
+ - Melanoma
127
+ - Dermatofibroma
128
+ - **Performance Metrics:**
129
+ - **Validation Accuracy:** 96.95%
130
+ - **Train Accuracy:** 96.14%
131
+ - **Loss Function:** Cross-Entropy
132
+ """)
133
 
134
+ # =======================
135
+ # Footer
136
+ # =======================
137
+ st.sidebar.info("""
138
+ Developed by **[mgbam](https://huggingface.co/mgbam)**
139
+ This app leverages state-of-the-art AI models for skin cancer detection and research insights.
140
+ """)