File size: 9,042 Bytes
cb2ce22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25b4ddf
cb2ce22
 
25b4ddf
 
cb2ce22
 
 
 
25b4ddf
cb2ce22
25b4ddf
 
 
 
 
 
cb2ce22
 
25b4ddf
 
 
 
 
cb2ce22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
"""
WASH CFM Topic Classification Gradio Application

This application provides a user interface for classifying WASH (Water, Sanitation,
and Hygiene) feedback using a fine-tuned ModernBERT model.

This is a Gradio implementation with identical functionality to wash_cfm_app.py.
"""

import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
from huggingface_hub import snapshot_download, hf_hub_download
import functools
import os
import tempfile

# ================================
# CONFIGURATION SECTION
# ================================
# Replace these with your actual Hugging Face repository details
HF_REPO_ID = "ibagur/wash_cfm_classifier"  # Your Hugging Face repository
HF_MODEL_CACHE_DIR = "/tmp/model_cache"  # Cache directory (using /tmp for better Space compatibility)
# ================================


@functools.lru_cache(maxsize=1)
def load_model():
    """
    Load the pre-trained WASH CFM classifier model from Hugging Face Hub and create a pipeline.
    Downloads the model at runtime if not already cached locally.
    Uses LRU cache to avoid reloading on every interaction.

    Returns:
        pipeline: Hugging Face transformers pipeline for text classification
    """
    print(f"Downloading model from Hugging Face Hub: {HF_REPO_ID}")
    print("This may take a few minutes on first run...")
    
    try:
        # Download the entire model repository to cache
        # This is more efficient than downloading individual files
        model_path = snapshot_download(
            repo_id=HF_REPO_ID,
            cache_dir=HF_MODEL_CACHE_DIR,
            resume_download=True,  # Resume if download was interrupted
            local_files_only=False  # Force download if not in cache
        )
        
        print(f"Model downloaded successfully to: {model_path}")
        
        # Load tokenizer and model from the downloaded path
        tokenizer = AutoTokenizer.from_pretrained(model_path)
        model = AutoModelForSequenceClassification.from_pretrained(model_path)

        # Set to evaluation mode
        model.eval()

        # Check what device we're using (including Apple Silicon MPS support)
        if torch.backends.mps.is_available():
            device = torch.device("mps")  # Apple Silicon
        elif torch.cuda.is_available():
            device = torch.device("cuda")  # NVIDIA GPU
        else:
            device = torch.device("cpu")  # CPU fallback

        print(f"Using device: {device}")

        model.to(device)

        # Create pipeline for easy inference
        classifier = pipeline(
            'text-classification',
            model=model,
            tokenizer=tokenizer,
            device=device
        )

        return classifier
        
    except Exception as e:
        print(f"Error downloading model: {str(e)}")
        print("\nTroubleshooting steps:")
        print("1. Check that your repository ID is correct")
        print("2. Ensure the repository is public or you have proper access")
        print("3. Check your internet connection")
        print("4. Verify the repository exists on Hugging Face Hub")
        raise


def predict_topics(text, classifier, top_k=2):
    """
    Predict the top-k most probable topics for the given text using the pipeline.

    Args:
        text (str): Input feedback text
        classifier: Hugging Face transformers pipeline
        top_k (int): Number of top predictions to return

    Returns:
        list: List of tuples (topic_name, probability)
    """
    # Use pipeline for prediction - it handles all the complexity internally
    predictions = classifier(text, top_k=top_k)
    
    # Convert pipeline results to our format
    results = [(pred['label'], pred['score']) for pred in predictions]
    
    return results


def classify_feedback(text):
    """
    Main classification handler for Gradio interface.

    Args:
        text (str): Input WASH feedback text

    Returns:
        str: HTML formatted prediction results
    """
    # Validate input
    if not text or not text.strip():
        return """
        <div style="
            background-color: #fff3cd;
            color: #856404;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid #ffc107;
            font-weight: 500;
        ">
            ⚠️ Please enter some feedback text.
        </div>
        """

    try:
        # Load classifier pipeline (cached)
        classifier = load_model()

        # Get predictions
        predictions = predict_topics(
            text,
            classifier,
            top_k=2
        )

        # Format results as HTML
        html_output = """
        <div style="margin-top: 10px;">
            <h3 style="color: #333; margin-bottom: 15px;">πŸ“Š Predicted Topics</h3>
        """

        for i, (topic, probability) in enumerate(predictions, 1):
            # Add prediction box with fixed color and enhanced specificity
            html_output += f"""
            <div style="
                background-color: #009999 !important;
                color: #ffffff !important;
                padding: 15px;
                border-radius: 8px;
                margin-bottom: 10px;
                font-weight: 500;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            ">
                <div style="
                    font-size: 16px; 
                    margin-bottom: 5px; 
                    color: #ffffff !important;
                    font-weight: 600;
                ">
                    {i}. {topic}
                </div>
                <div style="
                    font-size: 14px; 
                    opacity: 0.9;
                    color: #ffffff !important;
                ">
                    Confidence: {probability:.1%}
                </div>
            </div>
            """

        html_output += "</div>"
        return html_output

    except FileNotFoundError:
        return """
        <div style="
            background-color: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid #dc3545;
        ">
            <strong>❌ Error loading model</strong><br>
            Could not download or access the model from Hugging Face Hub.<br>
            Please check your internet connection and repository configuration.
        </div>
        """
    except Exception as e:
        return f"""
        <div style="
            background-color: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid #dc3545;
        ">
            <strong>❌ Error during prediction:</strong><br>
            {str(e)}
        </div>
        """


def clear_inputs():
    """
    Clear both input and output fields.

    Returns:
        tuple: Empty strings for textbox and output
    """
    return "", ""


def create_interface():
    """
    Create and configure the Gradio interface.

    Returns:
        gr.Blocks: Configured Gradio interface
    """
    with gr.Blocks(
        title="WASH CFM Topic Classifier",
        theme=gr.themes.Soft()
    ) as demo:
        # Header
        gr.Markdown("""
        # πŸ’§ WASH CFM Topic Classifier

        This application classifies WASH (Water, Sanitation, and Hygiene) feedback
        into relevant topic categories using a fine-tuned ModernBERT model.

        **Enter your feedback below and click Submit.**
        """)

        # Input section
        input_textbox = gr.Textbox(
            label="Enter WASH feedback:",
            placeholder="Example: The water pump in our area has been broken for 3 days...",
            lines=6,
            interactive=True
        )

        # Button row
        with gr.Row():
            submit_btn = gr.Button("➜ Submit", variant="primary", scale=2)
            clear_btn = gr.Button("πŸ—‘οΈ Clear", scale=1)

        # Output section
        output_html = gr.HTML(label="Results")

        # Footer
        gr.Markdown("""
        ---
        <div style="text-align: center; color: #666; font-size: 12px;">
            Powered by ModernBERT-large | UNICEF WASH Cluster CFM System
        </div>
        """)

        # Event handlers
        submit_btn.click(
            fn=classify_feedback,
            inputs=input_textbox,
            outputs=output_html
        )

        input_textbox.submit(
            fn=classify_feedback,
            inputs=input_textbox,
            outputs=output_html
        )

        clear_btn.click(
            fn=clear_inputs,
            inputs=None,
            outputs=[input_textbox, output_html]
        )

    return demo


def main():
    """
    Main function to launch the Gradio application.
    """
    demo = create_interface()

    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False
    )


if __name__ == "__main__":
    main()