File size: 10,060 Bytes
d1b509c
 
5092eb8
 
d1b509c
5092eb8
 
3a8ed2e
 
5092eb8
d1b509c
5092eb8
 
70e7566
5092eb8
70e7566
5092eb8
d1b509c
691b7fe
 
 
 
 
 
5092eb8
d1b509c
691b7fe
d1b509c
 
 
 
 
 
691b7fe
d1b509c
691b7fe
d1b509c
971f77f
d1b509c
70e7566
d1b509c
691b7fe
d1b509c
70e7566
d1b509c
971f77f
70e7566
3a8ed2e
d1b509c
3a8ed2e
d1b509c
3a8ed2e
 
 
691b7fe
3a8ed2e
 
4a1ab6f
 
 
 
 
 
 
 
 
 
 
3a8ed2e
 
70e7566
691b7fe
 
 
 
 
 
 
 
d1b509c
691b7fe
971f77f
691b7fe
 
70e7566
971f77f
691b7fe
70e7566
971f77f
691b7fe
971f77f
3a8ed2e
70e7566
5092eb8
d1b509c
5092eb8
d1b509c
5092eb8
7ce08d2
691b7fe
 
 
7ce08d2
691b7fe
 
 
 
 
 
 
 
 
d1b509c
 
691b7fe
971f77f
 
691b7fe
5092eb8
70e7566
5092eb8
4a1ab6f
 
 
1172915
4a1ab6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1172915
 
 
 
 
 
 
4a1ab6f
 
d1b509c
850d90a
4a1ab6f
 
1172915
 
 
4a1ab6f
 
 
 
 
 
 
 
 
 
 
 
 
1172915
4a1ab6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1172915
4a1ab6f
 
 
 
 
 
 
 
 
 
 
 
 
 
1172915
4a1ab6f
 
 
 
 
 
 
 
 
 
 
 
 
 
850d90a
4a1ab6f
1172915
4a1ab6f
 
 
 
 
 
 
 
 
850d90a
70e7566
850d90a
 
 
 
 
70e7566
850d90a
5092eb8
691b7fe
850d90a
 
 
 
4a1ab6f
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
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
    )