import gradio as gr from PIL import Image, ImageStat import numpy as np import io import math print("๐Ÿš€ Glow AI - Skin Analysis Tool Starting...") print("Using pure image processing (no ML models)") def analyze_skin_detailed(image): """Advanced skin analysis using image processing techniques""" if image is None: return "โŒ Please upload an image first.", None try: # Convert to PIL if needed if isinstance(image, np.ndarray): pil_image = Image.fromarray(image) else: pil_image = image # Store original for display original = pil_image.copy() # Resize for analysis pil_image = pil_image.resize((400, 400)) # Convert to RGB if needed if pil_image.mode != 'RGB': pil_image = pil_image.convert('RGB') # Get image stats width, height = pil_image.size # Basic validation if width < 100 or height < 100: return "โš ๏ธ Image too small. Please upload a clearer photo.", original # Convert to numpy array img_array = np.array(pil_image) r_avg = np.mean(img_array[:,:,0]) g_avg = np.mean(img_array[:,:,1]) b_avg = np.mean(img_array[:,:,2]) # Calculate overall brightness brightness = (r_avg + g_avg + b_avg) / 3 # Calculate grayscale for texture analysis gray = np.dot(img_array[...,:3], [0.2989, 0.5870, 0.1140]) # === COLOR ANALYSIS === # Determine dominant color if r_avg > g_avg and r_avg > b_avg: dominant = "๐Ÿ”ด Red/Warm tones" if r_avg - g_avg > 30: condition_name = "Redness / Inflammation" condition_confidence = min(85, (r_avg - g_avg) / 3) condition_advice = "Use gentle, soothing products. Avoid harsh ingredients. Consider consulting a dermatologist." else: condition_name = "Warm Skin Undertones" condition_confidence = 65 condition_advice = "Your skin shows warm undertones. Look for products with golden or peachy tones." elif g_avg > r_avg and g_avg > b_avg: dominant = "๐ŸŸข Greenish tones" condition_name = "Potential Skin Sensitivity" condition_confidence = 55 condition_advice = "This coloring may indicate certain conditions. Please consult a dermatologist." else: dominant = "โšช Neutral/Cool tones" condition_name = "Neutral Skin Undertones" condition_confidence = 75 condition_advice = "Your skin shows cool undertones. Look for products with pink or blue undertones." # === TEXTURE ANALYSIS === r_std = np.std(img_array[:,:,0]) g_std = np.std(img_array[:,:,1]) b_std = np.std(img_array[:,:,2]) texture_score = (r_std + g_std + b_std) / 3 if texture_score > 60: texture_result = "โš ๏ธ Noticeable texture variation" texture_confidence = 70 elif texture_score > 40: texture_result = "๐Ÿ“Š Moderate texture" texture_confidence = 60 else: texture_result = "โœ… Smooth texture" texture_confidence = 80 # === LIGHTING ANALYSIS === if brightness < 80: lighting_result = "โŒ Too Dark" lighting_confidence = 85 lighting_advice = "Please use better lighting for more accurate analysis" elif brightness > 200: lighting_result = "โŒ Too Bright / Overexposed" lighting_confidence = 85 lighting_advice = "Please reduce lighting for more accurate analysis" else: lighting_result = "โœ… Good" lighting_confidence = 90 lighting_advice = "Lighting conditions are optimal" # === OILINESS DETECTION === highlights = np.sum(gray > 200) highlight_percent = (highlights / (width * height)) * 100 if highlight_percent > 15: oiliness_name = "High Oiliness" oiliness_confidence = min(85, highlight_percent * 2) oiliness_advice = "Use oil-free, non-comedogenic products. Cleanse twice daily. Consider salicylic acid." elif highlight_percent > 5: oiliness_name = "Moderate Oiliness" oiliness_confidence = 60 oiliness_advice = "Maintain balanced cleansing. Use lightweight, oil-free moisturizers." else: oiliness_name = "Normal Oil Levels" oiliness_confidence = 75 oiliness_advice = "Your oil production appears balanced. Continue with your current routine." # === PIGMENTATION DETECTION === darkness_threshold = brightness * 0.6 dark_pixels = np.sum(gray < darkness_threshold) dark_percent = (dark_pixels / (width * height)) * 100 if dark_percent > 20: pigmentation_name = "Hyperpigmentation / Dark Spots" pigmentation_confidence = min(80, dark_percent * 1.5) pigmentation_advice = "Use Vitamin C serum daily. Always wear SPF 50+. Consider niacinamide for brightening." elif dark_percent > 8: pigmentation_name = "Uneven Pigmentation" pigmentation_confidence = 55 pigmentation_advice = "Consider incorporating brightening ingredients like Vitamin C or alpha arbutin." else: pigmentation_name = "Even Pigmentation" pigmentation_confidence = 85 pigmentation_advice = "Your skin tone appears even. Continue with sun protection to maintain it." # === BUILD OUTPUT HTML === output = f"""

โœจ Glow AI Analysis Report

Image Processing Analysis

๐Ÿ“Š Image Quality

๐Ÿ’ก Lighting: {lighting_result} (Confidence: {lighting_confidence:.0f}%)

๐ŸŽจ Dominant Color: {dominant}

โœจ Texture: {texture_result} (Confidence: {texture_confidence:.0f}%)

โ˜€๏ธ Brightness: {brightness:.0f}/255

๐Ÿ’ก {lighting_advice}

๐Ÿ” Analysis Results

๐Ÿฉธ {condition_name} {condition_confidence:.0f}%

๐Ÿ’ก {condition_advice}

๐Ÿ’ง {oiliness_name} {oiliness_confidence:.0f}%

๐Ÿ’ก {oiliness_advice}

๐ŸŽจ {pigmentation_name} {pigmentation_confidence:.0f}%

๐Ÿ’ก {pigmentation_advice}

๐Ÿ’ก Daily Skincare Routine

โš•๏ธ Medical Disclaimer

This analysis is for INFORMATIONAL purposes only and is NOT a medical diagnosis.

๐Ÿšซ This tool cannot detect skin cancer, serious conditions, or replace professional medical advice.

โœ… Please consult a dermatologist if you have:

""" return output, original except Exception as e: return f"โŒ Error analyzing image: {str(e)}", image def clear_all(): """Clear all inputs and outputs""" return None, None, None # Create the Gradio interface with gr.Blocks(title="Glow AI - Skin Analysis", theme=gr.themes.Soft()) as demo: gr.Markdown(""" # โœจ Glow AI - Skin Analysis ### Upload a clear, well-lit photo of your skin """) gr.Markdown("โœ… **Active:** Real-time image processing analysis") with gr.Row(): with gr.Column(): image_input = gr.Image(type="pil", label="๐Ÿ“ธ Upload Photo", height=350) with gr.Row(): analyze_btn = gr.Button("๐Ÿ”ฌ Analyze", variant="primary", size="lg") clear_btn = gr.Button("๐Ÿ—‘๏ธ Clear", variant="secondary") gr.Markdown(""" ### ๐Ÿ“‹ Tips: - Use natural lighting - Take a clear, focused photo - Remove makeup if possible """) with gr.Column(): output_text = gr.HTML("### ๐Ÿ“Š Click 'Analyze' to start") output_image = gr.Image(label="๐Ÿ“ท Your Image", height=250) analyze_btn.click( fn=analyze_skin_detailed, inputs=[image_input], outputs=[output_text, output_image] ) clear_btn.click( fn=clear_all, inputs=[], outputs=[image_input, output_text, output_image] ) if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860)