Spaces:
Sleeping
Sleeping
import os | |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Suppress TensorFlow warnings | |
import gradio as gr | |
import tensorflow as tf | |
from tensorflow.keras.models import load_model | |
import numpy as np | |
from PIL import Image | |
import requests | |
import json | |
# ================== MODEL LOADING ================== | |
try: | |
model = load_model('wound_classifier_model_googlenet.h5') | |
print("β Model loaded successfully") | |
except Exception as e: | |
raise RuntimeError(f"β Model loading failed: {str(e)}") | |
# ================== CLASS LABELS ================== | |
CLASS_LABELS = [ | |
"Abrasions", "Bruises", "Burns", "Cut", "Diabetic Wounds", "Gingivitis", | |
"Surgical Wounds", "Venous Wounds", "athlete foot", "cellulitis", | |
"chickenpox", "cutaneous larva migrans", "impetigo", "nail fungus", | |
"ringworm", "shingles", "tooth discoloration", "ulcer" | |
] | |
# Verify model compatibility | |
assert len(CLASS_LABELS) == model.output_shape[-1], \ | |
f"Class mismatch: Model expects {model.output_shape[-1]} classes, found {len(CLASS_LABELS)}" | |
# ================== OPENROUTER CONFIG ================== | |
OPENROUTER_API_KEY = "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" | |
OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions" | |
MODEL_NAME = "mistralai/mistral-7b-instruct" | |
# ================== IMAGE PROCESSING ================== | |
def preprocess_image(image, target_size=(224, 224)): | |
"""Process and validate input images""" | |
try: | |
if not image: | |
raise ValueError("π¨ No image provided") | |
image = image.convert("RGB").resize(target_size) | |
array = np.array(image) / 255.0 | |
print(f"πΌοΈ Image processed: Shape {array.shape}") | |
return array | |
except Exception as e: | |
raise RuntimeError(f"πΌοΈ Image processing failed: {str(e)}") | |
# ================== MEDICAL GUIDELINES ================== | |
def get_medical_guidelines(wound_type): | |
"""Fetch treatment guidelines from OpenRouter API""" | |
headers = { | |
"Authorization": f"Bearer {OPENROUTER_API_KEY}", | |
"Content-Type": "application/json", | |
"HTTP-Referer": "https://huggingface.co/spaces/MahatirTusher/Wound_Treatment" | |
} | |
prompt = f"""You are a medical expert providing guidance for a patient with {wound_type}. | |
First, briefly introduce what {wound_type} are and their typical characteristics. | |
Then, provide a comprehensive care guide including: | |
1. Immediate First Aid Steps | |
2. Home Care Instructions | |
3. Prevention Tips | |
4. Warning Signs (when to seek emergency care) | |
Format your response in clear sections with proper spacing. Use simple, | |
non-technical language that a general audience can understand.""" | |
try: | |
print(f"π‘ Sending API request for {wound_type}...") | |
response = requests.post( | |
OPENROUTER_API_URL, | |
headers=headers, | |
json={ | |
"model": MODEL_NAME, | |
"messages": [{"role": "user", "content": prompt}], | |
"temperature": 0.5 | |
}, | |
timeout=20 | |
) | |
response.raise_for_status() | |
result = response.json() | |
print("π§ Raw API response:", json.dumps(result, indent=2)) | |
if not result.get("choices"): | |
return "β οΈ API response format unexpected" | |
return result["choices"][0]["message"]["content"] | |
except Exception as e: | |
return f"β οΈ Guidelines unavailable: {str(e)}" | |
# ================== MAIN PREDICTION ================== | |
def predict(image): | |
"""Complete prediction pipeline""" | |
try: | |
# Preprocess image | |
processed_img = preprocess_image(image) | |
input_tensor = np.expand_dims(processed_img, axis=0) | |
# Make prediction | |
predictions = model.predict(input_tensor)[0] | |
sorted_indices = np.argsort(predictions)[::-1] # Descending order | |
# Format results | |
results = { | |
CLASS_LABELS[i]: float(predictions[i]) | |
for i in sorted_indices[:3] # Top 3 predictions | |
} | |
top_class = CLASS_LABELS[sorted_indices[0]] | |
# Get guidelines | |
guidelines = get_medical_guidelines(top_class) | |
return results, guidelines | |
except Exception as e: | |
return {f"π¨ Error": str(e)}, "" | |
# ================== CSS STYLES ================== | |
custom_css = """ | |
.gradio-container { | |
font-family: 'Times New Roman', Times, serif !important; | |
} | |
.container { | |
background: rgba(255, 255, 255, 0.9); | |
border-radius: 20px; | |
padding: 2rem; | |
box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37); | |
backdrop-filter: blur(4px); | |
border: 1px solid rgba(255, 255, 255, 0.18); | |
margin: 1rem 0; | |
} | |
.title { | |
color: #2D3748; | |
text-align: center; | |
font-size: 2.5rem; | |
margin-bottom: 1rem; | |
} | |
.subtitle { | |
color: #4A5568; | |
text-align: center; | |
font-size: 1.2rem; | |
margin-bottom: 2rem; | |
} | |
.warning { | |
background-color: #FED7D7; | |
border-left: 4px solid #F56565; | |
padding: 1rem; | |
margin: 1rem 0; | |
border-radius: 8px; | |
} | |
.info-section { | |
background-color: #E6F6FF; | |
border-radius: 12px; | |
padding: 1.5rem; | |
margin: 1rem 0; | |
} | |
.guidelines-box { | |
background: #F7FAFC; | |
border-radius: 10px; | |
padding: 1rem; | |
margin-top: 1rem; | |
} | |
""" | |
# ================== GRADIO INTERFACE ================== | |
def create_interface(): | |
with gr.Blocks(css=custom_css, title="WoundWise AI") as demo: | |
# Logo and Introduction | |
with gr.Column(elem_classes="container"): | |
gr.Image("logo.png", show_label=False, container=False) | |
gr.Markdown("# Welcome to WoundWise AI") | |
gr.Markdown(""" | |
In today's fast-paced world, early detection of medical conditions can be a game-changer. | |
WoundWise AI is a cutting-edge AI-powered wound classification system developed as part | |
of EarlyMed, an initiative by students of Vellore Institute of Technology. Our mission | |
is simple yet impactful: "Early Detection, Smarter Decision." | |
By leveraging deep learning, this system analyzes wound images to provide accurate | |
classifications and essential treatment guidelines. Whether it's a minor cut or a | |
serious skin condition, our AI assists in identifying potential risks, helping users | |
make informed health decisions at an early stage. | |
""") | |
# Main Interface | |
with gr.Column(elem_classes="container"): | |
gr.Markdown("## πΈ Upload or Capture Wound Image") | |
gr.Markdown("Use your device's camera or upload an existing image") | |
file_input = gr.Image(type="pil", label="Upload Wound Image") | |
submit_btn = gr.Button("Analyze Now", variant="primary") | |
# Example Images | |
gr.Examples( | |
examples=["abrasion.jpg", "burn.png", "bruise.png", "chicken-pox.png", "cut.png"], | |
inputs=file_input, | |
label="Example Images" | |
) | |
output_label = gr.Label(label="Analysis Results", num_top_classes=3) | |
output_guidelines = gr.Textbox( | |
label="Medical Guidelines", | |
lines=12, | |
elem_classes="guidelines-box" | |
) | |
# Why Care About Wounds | |
with gr.Column(elem_classes="info-section"): | |
gr.Markdown(""" | |
## β οΈ Why Wound Care Matters | |
Ignoring wounds can lead to serious complications: | |
- Risk of bacterial infection | |
- Delayed healing and scarring | |
- Chronic wound development | |
- Systemic health issues | |
- Increased medical costs | |
Early intervention and proper care are crucial for optimal healing and preventing complications. | |
""") | |
# How Our Model Works | |
with gr.Column(elem_classes="info-section"): | |
gr.Markdown(""" | |
## π¬ Our Technology | |
WoundWise AI uses a state-of-the-art deep learning model based on the GoogLeNet | |
architecture, trained on thousands of medical images. The system: | |
1. Analyzes wound images using advanced computer vision | |
2. Identifies 18 different types of wounds and skin conditions | |
3. Provides real-time classification with confidence scores | |
4. Generates medical guidelines using advanced AI | |
Our model achieves high accuracy through extensive training and validation by | |
medical professionals. | |
""") | |
# Disclaimer | |
with gr.Column(elem_classes="warning"): | |
gr.Markdown(""" | |
## βοΈ Medical Disclaimer | |
This AI system is designed to assist in preliminary wound assessment only. It is not | |
a substitute for professional medical advice, diagnosis, or treatment. Always seek | |
the advice of qualified healthcare providers with any questions regarding your | |
medical condition. If you believe your wound is serious or life-threatening, | |
please seek immediate medical attention. | |
""") | |
# Connect input to processing | |
submit_btn.click( | |
fn=predict, | |
inputs=[file_input], | |
outputs=[output_label, output_guidelines] | |
) | |
return demo | |
if __name__ == "__main__": | |
iface = create_interface() | |
iface.launch( | |
server_name="0.0.0.0", | |
server_port=7860, | |
share=True | |
) |