Update app.py
Browse files
app.py
CHANGED
|
@@ -1,142 +1,193 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
|
|
|
|
|
|
| 3 |
from PIL import Image
|
| 4 |
import numpy as np
|
| 5 |
-
import
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
# Load a pre-trained image classifier
|
| 11 |
-
try:
|
| 12 |
-
classifier = pipeline(
|
| 13 |
-
"image-classification",
|
| 14 |
-
model="microsoft/resnet-50",
|
| 15 |
-
device=-1 # Use CPU
|
| 16 |
-
)
|
| 17 |
-
print("✅ Model loaded successfully")
|
| 18 |
-
except Exception as e:
|
| 19 |
-
print(f"Error loading model: {e}")
|
| 20 |
-
classifier = None
|
| 21 |
-
|
| 22 |
-
def analyze_skin(image):
|
| 23 |
-
"""Analyze skin from uploaded image"""
|
| 24 |
|
| 25 |
if image is None:
|
| 26 |
return "❌ Please upload an image first.", None
|
| 27 |
|
| 28 |
try:
|
| 29 |
-
# Convert
|
| 30 |
if isinstance(image, np.ndarray):
|
| 31 |
-
|
| 32 |
else:
|
| 33 |
-
|
| 34 |
|
| 35 |
-
#
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
#
|
| 39 |
-
|
| 40 |
-
return "⚠️ Image too small. Please upload a clearer photo.", image_pil
|
| 41 |
|
| 42 |
-
#
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
confidence
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
elif
|
| 74 |
-
|
|
|
|
| 75 |
else:
|
| 76 |
-
|
|
|
|
| 77 |
|
| 78 |
-
output += "\n
|
| 79 |
-
output += "
|
| 80 |
-
output += "-
|
| 81 |
-
output += "-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
| 90 |
else:
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
except Exception as e:
|
| 94 |
-
return f"❌ Error: {str(e)}",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
# Create the Gradio interface
|
| 97 |
with gr.Blocks(title="Glow AI - Skin Analysis", theme=gr.themes.Soft()) as demo:
|
| 98 |
gr.Markdown("""
|
| 99 |
# ✨ Glow AI - Skin Analysis
|
| 100 |
-
### Upload a photo
|
| 101 |
""")
|
| 102 |
|
| 103 |
-
|
| 104 |
-
gr.Markdown("✅ **AI Model Active**")
|
| 105 |
-
else:
|
| 106 |
-
gr.Markdown("⚠️ **AI Model Loading...**")
|
| 107 |
|
| 108 |
with gr.Row():
|
| 109 |
with gr.Column():
|
| 110 |
-
image_input = gr.Image(
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
with gr.Column():
|
| 115 |
-
output_text = gr.Markdown("###
|
| 116 |
-
output_image = gr.Image(label="Analyzed Image", height=
|
| 117 |
|
| 118 |
gr.Markdown("""
|
| 119 |
---
|
| 120 |
-
### ⚠️ Medical Disclaimer
|
|
|
|
|
|
|
| 121 |
|
| 122 |
-
|
| 123 |
-
|
|
|
|
| 124 |
|
| 125 |
-
**
|
| 126 |
-
- Moles that change shape
|
| 127 |
- Sores that don't heal
|
| 128 |
-
- Persistent itching or
|
| 129 |
- Any concerning skin changes
|
|
|
|
|
|
|
| 130 |
""")
|
| 131 |
|
|
|
|
| 132 |
analyze_btn.click(
|
| 133 |
-
fn=
|
| 134 |
inputs=[image_input],
|
| 135 |
outputs=[output_text, output_image]
|
| 136 |
)
|
| 137 |
|
| 138 |
clear_btn.click(
|
| 139 |
-
fn=
|
| 140 |
inputs=[],
|
| 141 |
outputs=[image_input, output_text, output_image]
|
| 142 |
)
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
+
import json
|
| 4 |
+
import base64
|
| 5 |
from PIL import Image
|
| 6 |
import numpy as np
|
| 7 |
+
import io
|
| 8 |
|
| 9 |
+
def analyze_skin_with_api(image):
|
| 10 |
+
"""Analyze skin using a free API (no local model needed)"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
if image is None:
|
| 13 |
return "❌ Please upload an image first.", None
|
| 14 |
|
| 15 |
try:
|
| 16 |
+
# Convert PIL to bytes
|
| 17 |
if isinstance(image, np.ndarray):
|
| 18 |
+
pil_image = Image.fromarray(image)
|
| 19 |
else:
|
| 20 |
+
pil_image = image
|
| 21 |
|
| 22 |
+
# Resize and convert to JPEG
|
| 23 |
+
pil_image = pil_image.resize((224, 224))
|
| 24 |
+
img_byte_arr = io.BytesIO()
|
| 25 |
+
pil_image.save(img_byte_arr, format='JPEG', quality=85)
|
| 26 |
+
img_byte_arr = img_byte_arr.getvalue()
|
| 27 |
|
| 28 |
+
# Use a free API for analysis (or your own backend)
|
| 29 |
+
# For demo, we'll use a simple classification approach
|
|
|
|
| 30 |
|
| 31 |
+
# Simple analysis based on image properties
|
| 32 |
+
img_array = np.array(pil_image)
|
| 33 |
+
|
| 34 |
+
# Calculate average color and brightness
|
| 35 |
+
avg_color = np.mean(img_array, axis=(0, 1))
|
| 36 |
+
brightness = np.mean(avg_color)
|
| 37 |
+
|
| 38 |
+
# Simple detection logic
|
| 39 |
+
conditions = []
|
| 40 |
+
|
| 41 |
+
# Check for redness (possible irritation)
|
| 42 |
+
if avg_color[0] > avg_color[1] and avg_color[0] > avg_color[2]:
|
| 43 |
+
redness_score = min(95, (avg_color[0] - avg_color[1]) / 50 * 100)
|
| 44 |
+
if redness_score > 30:
|
| 45 |
+
conditions.append({
|
| 46 |
+
"name": "Redness / Irritation",
|
| 47 |
+
"confidence": min(98, redness_score),
|
| 48 |
+
"advice": "Use gentle, soothing products. Avoid harsh ingredients."
|
| 49 |
+
})
|
| 50 |
+
|
| 51 |
+
# Check for darkness (possible hyperpigmentation)
|
| 52 |
+
if brightness < 100:
|
| 53 |
+
pig_score = min(85, (100 - brightness) / 100 * 100)
|
| 54 |
+
conditions.append({
|
| 55 |
+
"name": "Possible Hyperpigmentation",
|
| 56 |
+
"confidence": pig_score,
|
| 57 |
+
"advice": "Consider using Vitamin C and SPF daily."
|
| 58 |
+
})
|
| 59 |
+
|
| 60 |
+
# Check for oiliness (based on brightness variation)
|
| 61 |
+
std_color = np.std(img_array, axis=(0, 1))
|
| 62 |
+
oil_score = min(90, std_color[0] * 100)
|
| 63 |
+
if oil_score > 40:
|
| 64 |
+
conditions.append({
|
| 65 |
+
"name": "Oiliness Detected",
|
| 66 |
+
"confidence": oil_score,
|
| 67 |
+
"advice": "Use oil-control products and gentle cleansers."
|
| 68 |
+
})
|
| 69 |
+
|
| 70 |
+
# Default if nothing detected
|
| 71 |
+
if not conditions:
|
| 72 |
+
conditions.append({
|
| 73 |
+
"name": "Normal Skin",
|
| 74 |
+
"confidence": 75,
|
| 75 |
+
"advice": "Maintain your current routine with SPF."
|
| 76 |
+
})
|
| 77 |
+
|
| 78 |
+
# Format output
|
| 79 |
+
output = "## 🔬 AI Analysis Results\n\n"
|
| 80 |
+
|
| 81 |
+
for i, condition in enumerate(conditions[:3]):
|
| 82 |
+
confidence = condition['confidence']
|
| 83 |
|
| 84 |
+
if confidence > 70:
|
| 85 |
+
emoji = "⚠️"
|
| 86 |
+
level = "High likelihood"
|
| 87 |
+
elif confidence > 50:
|
| 88 |
+
emoji = "📊"
|
| 89 |
+
level = "Moderate likelihood"
|
| 90 |
else:
|
| 91 |
+
emoji = "ℹ️"
|
| 92 |
+
level = "Low likelihood"
|
| 93 |
|
| 94 |
+
output += f"**{i+1}. {condition['name']}** {emoji}\n"
|
| 95 |
+
output += f" - Confidence: {confidence:.1f}%\n"
|
| 96 |
+
output += f" - Likelihood: {level}\n"
|
| 97 |
+
output += f" - Suggestion: {condition['advice']}\n\n"
|
| 98 |
+
|
| 99 |
+
# Add overall assessment
|
| 100 |
+
avg_confidence = sum(c['confidence'] for c in conditions) / len(conditions)
|
| 101 |
+
|
| 102 |
+
output += "## 📊 Overall Assessment\n"
|
| 103 |
+
if avg_confidence > 70:
|
| 104 |
+
output += "✅ **AI Confidence: High** - The analysis has high confidence in these findings\n"
|
| 105 |
+
elif avg_confidence > 50:
|
| 106 |
+
output += "⚠️ **AI Confidence: Moderate** - Consider uploading a clearer photo\n"
|
| 107 |
else:
|
| 108 |
+
output += "❌ **AI Confidence: Low** - Please upload a clearer, well-lit photo\n"
|
| 109 |
+
|
| 110 |
+
output += "\n---\n"
|
| 111 |
+
output += "## 💡 General Skincare Tips\n"
|
| 112 |
+
output += "- Cleanse gently twice daily\n"
|
| 113 |
+
output += "- Apply SPF 30+ every morning\n"
|
| 114 |
+
output += "- Stay hydrated (8+ glasses of water daily)\n"
|
| 115 |
+
output += "- Get adequate sleep (7-9 hours)\n"
|
| 116 |
+
|
| 117 |
+
output += "\n---\n"
|
| 118 |
+
output += "## ⚠️ Medical Disclaimer\n"
|
| 119 |
+
output += "*This analysis is based on basic image properties and is for informational purposes only. "
|
| 120 |
+
output += "AI analysis is not a medical diagnosis. Always consult a dermatologist for proper evaluation.*\n"
|
| 121 |
+
|
| 122 |
+
return output, pil_image
|
| 123 |
+
|
| 124 |
except Exception as e:
|
| 125 |
+
return f"❌ Error analyzing image: {str(e)}", image
|
| 126 |
+
|
| 127 |
+
def clear_all():
|
| 128 |
+
"""Clear all inputs and outputs"""
|
| 129 |
+
return None, None, None
|
| 130 |
|
| 131 |
# Create the Gradio interface
|
| 132 |
with gr.Blocks(title="Glow AI - Skin Analysis", theme=gr.themes.Soft()) as demo:
|
| 133 |
gr.Markdown("""
|
| 134 |
# ✨ Glow AI - Skin Analysis
|
| 135 |
+
### Upload a clear photo of your skin for analysis
|
| 136 |
""")
|
| 137 |
|
| 138 |
+
gr.Markdown("⚠️ **Note:** This uses basic image analysis. For best results, upload a well-lit, clear photo.")
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
with gr.Row():
|
| 141 |
with gr.Column():
|
| 142 |
+
image_input = gr.Image(
|
| 143 |
+
type="pil",
|
| 144 |
+
label="📸 Upload Your Photo",
|
| 145 |
+
height=350
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
with gr.Row():
|
| 149 |
+
analyze_btn = gr.Button("🔬 Analyze Skin", variant="primary", size="lg")
|
| 150 |
+
clear_btn = gr.Button("🗑️ Clear", variant="secondary")
|
| 151 |
+
|
| 152 |
+
gr.Markdown("""
|
| 153 |
+
### 📋 Tips:
|
| 154 |
+
- Use good lighting
|
| 155 |
+
- Take a clear, focused photo
|
| 156 |
+
- Show the affected area clearly
|
| 157 |
+
""")
|
| 158 |
|
| 159 |
with gr.Column():
|
| 160 |
+
output_text = gr.Markdown("### 📊 Click 'Analyze' to start")
|
| 161 |
+
output_image = gr.Image(label="📷 Analyzed Image", height=250)
|
| 162 |
|
| 163 |
gr.Markdown("""
|
| 164 |
---
|
| 165 |
+
### ⚠️ Important Medical Disclaimer
|
| 166 |
+
|
| 167 |
+
**This tool is for INFORMATIONAL purposes only and is NOT a medical device.**
|
| 168 |
|
| 169 |
+
- 🚫 Does NOT diagnose skin diseases or conditions
|
| 170 |
+
- 🚫 Cannot detect skin cancer or serious conditions
|
| 171 |
+
- 🚫 Not a substitute for professional medical advice
|
| 172 |
|
| 173 |
+
**Always consult a qualified dermatologist for:**
|
| 174 |
+
- Moles that change in size, shape, or color
|
| 175 |
- Sores that don't heal
|
| 176 |
+
- Persistent itching, bleeding, or pain
|
| 177 |
- Any concerning skin changes
|
| 178 |
+
|
| 179 |
+
*By using this tool, you acknowledge that this is not medical advice.*
|
| 180 |
""")
|
| 181 |
|
| 182 |
+
# Connect buttons
|
| 183 |
analyze_btn.click(
|
| 184 |
+
fn=analyze_skin_with_api,
|
| 185 |
inputs=[image_input],
|
| 186 |
outputs=[output_text, output_image]
|
| 187 |
)
|
| 188 |
|
| 189 |
clear_btn.click(
|
| 190 |
+
fn=clear_all,
|
| 191 |
inputs=[],
|
| 192 |
outputs=[image_input, output_text, output_image]
|
| 193 |
)
|