Spaces:
				
			
			
	
			
			
		Sleeping
		
	
	
	
			
			
	
	
	
	
		
		
		Sleeping
		
	Upload 4 files
Browse files- app.py +273 -0
- polluted_river1.jpg +0 -0
- polluted_river2.jpg +0 -0
- requirements.txt +6 -0
    	
        app.py
    ADDED
    
    | @@ -0,0 +1,273 @@ | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | 
|  | |
| 1 | 
            +
            # app.py
         | 
| 2 | 
            +
            import torch
         | 
| 3 | 
            +
            from transformers import InstructBlipProcessor, InstructBlipForConditionalGeneration
         | 
| 4 | 
            +
            import gradio as gr
         | 
| 5 | 
            +
            from PIL import Image
         | 
| 6 | 
            +
            import re
         | 
| 7 | 
            +
            from typing import List, Tuple
         | 
| 8 | 
            +
            import os
         | 
| 9 | 
            +
             | 
| 10 | 
            +
             | 
| 11 | 
            +
            class RiverPollutionAnalyzer:
         | 
| 12 | 
            +
                def __init__(self):
         | 
| 13 | 
            +
                    # Check if CUDA is available
         | 
| 14 | 
            +
                    self.device = "cuda" if torch.cuda.is_available() else "cpu"
         | 
| 15 | 
            +
             | 
| 16 | 
            +
                    # Load model with appropriate settings for Spaces
         | 
| 17 | 
            +
                    self.processor = InstructBlipProcessor.from_pretrained(
         | 
| 18 | 
            +
                        "Salesforce/instructblip-vicuna-7b"
         | 
| 19 | 
            +
                    )
         | 
| 20 | 
            +
             | 
| 21 | 
            +
                    # Simplified model loading for Spaces compatibility
         | 
| 22 | 
            +
                    self.model = InstructBlipForConditionalGeneration.from_pretrained(
         | 
| 23 | 
            +
                        "Salesforce/instructblip-vicuna-7b",
         | 
| 24 | 
            +
                        device_map="auto",
         | 
| 25 | 
            +
                        torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
         | 
| 26 | 
            +
                    ).to(self.device)
         | 
| 27 | 
            +
             | 
| 28 | 
            +
                    self.pollutants = [
         | 
| 29 | 
            +
                        "plastic waste",
         | 
| 30 | 
            +
                        "chemical foam",
         | 
| 31 | 
            +
                        "industrial discharge",
         | 
| 32 | 
            +
                        "sewage water",
         | 
| 33 | 
            +
                        "oil spill",
         | 
| 34 | 
            +
                        "organic debris",
         | 
| 35 | 
            +
                        "construction waste",
         | 
| 36 | 
            +
                        "medical waste",
         | 
| 37 | 
            +
                        "floating trash",
         | 
| 38 | 
            +
                        "algal bloom",
         | 
| 39 | 
            +
                        "toxic sludge",
         | 
| 40 | 
            +
                        "agricultural runoff",
         | 
| 41 | 
            +
                    ]
         | 
| 42 | 
            +
             | 
| 43 | 
            +
                    self.severity_descriptions = {
         | 
| 44 | 
            +
                        1: "Minimal pollution - Slightly noticeable",
         | 
| 45 | 
            +
                        2: "Minor pollution - Small amounts visible",
         | 
| 46 | 
            +
                        3: "Moderate pollution - Clearly visible",
         | 
| 47 | 
            +
                        4: "Significant pollution - Affecting water quality",
         | 
| 48 | 
            +
                        5: "Heavy pollution - Obvious environmental impact",
         | 
| 49 | 
            +
                        6: "Severe pollution - Large accumulation",
         | 
| 50 | 
            +
                        7: "Very severe pollution - Major ecosystem impact",
         | 
| 51 | 
            +
                        8: "Extreme pollution - Dangerous levels",
         | 
| 52 | 
            +
                        9: "Critical pollution - Immediate action needed",
         | 
| 53 | 
            +
                        10: "Disaster level - Ecological catastrophe",
         | 
| 54 | 
            +
                    }
         | 
| 55 | 
            +
             | 
| 56 | 
            +
                def analyze_image(self, image):
         | 
| 57 | 
            +
                    """Analyze river pollution with robust parsing"""
         | 
| 58 | 
            +
                    if not isinstance(image, Image.Image):
         | 
| 59 | 
            +
                        image = Image.fromarray(image)
         | 
| 60 | 
            +
             | 
| 61 | 
            +
                    prompt = """Analyze this river pollution scene and provide:
         | 
| 62 | 
            +
            1. List ALL visible pollutants ONLY from: [plastic waste, chemical foam, industrial discharge, sewage water, oil spill, organic debris, construction waste, medical waste, floating trash, algal bloom, toxic sludge, agricultural runoff]
         | 
| 63 | 
            +
            2. Estimate pollution severity from 1-10
         | 
| 64 | 
            +
             | 
| 65 | 
            +
            Respond EXACTLY in this format:
         | 
| 66 | 
            +
            Pollutants: [comma separated list]
         | 
| 67 | 
            +
            Severity: [number]"""
         | 
| 68 | 
            +
             | 
| 69 | 
            +
                    inputs = self.processor(images=image, text=prompt, return_tensors="pt").to(
         | 
| 70 | 
            +
                        self.device
         | 
| 71 | 
            +
                    )
         | 
| 72 | 
            +
             | 
| 73 | 
            +
                    with torch.no_grad():
         | 
| 74 | 
            +
                        outputs = self.model.generate(
         | 
| 75 | 
            +
                            **inputs,
         | 
| 76 | 
            +
                            max_new_tokens=200,
         | 
| 77 | 
            +
                            temperature=0.5,
         | 
| 78 | 
            +
                            top_p=0.85,
         | 
| 79 | 
            +
                            do_sample=True,
         | 
| 80 | 
            +
                        )
         | 
| 81 | 
            +
             | 
| 82 | 
            +
                    analysis = self.processor.batch_decode(outputs, skip_special_tokens=True)[0]
         | 
| 83 | 
            +
                    pollutants, severity = self._parse_response(analysis)
         | 
| 84 | 
            +
                    return self._format_analysis(pollutants, severity)
         | 
| 85 | 
            +
             | 
| 86 | 
            +
                def _parse_response(self, analysis: str) -> Tuple[List[str], int]:
         | 
| 87 | 
            +
                    """Robust parsing of model response"""
         | 
| 88 | 
            +
                    pollutants = []
         | 
| 89 | 
            +
                    severity = 3
         | 
| 90 | 
            +
             | 
| 91 | 
            +
                    # Extract pollutants
         | 
| 92 | 
            +
                    pollutant_match = re.search(
         | 
| 93 | 
            +
                        r"(?i)(pollutants?|contaminants?)[:\s]*\[?(.*?)(?:\]|Severity|severity|$)",
         | 
| 94 | 
            +
                        analysis,
         | 
| 95 | 
            +
                    )
         | 
| 96 | 
            +
             | 
| 97 | 
            +
                    if pollutant_match:
         | 
| 98 | 
            +
                        pollutants_str = pollutant_match.group(2).strip()
         | 
| 99 | 
            +
                        pollutants = [
         | 
| 100 | 
            +
                            p.strip().lower()
         | 
| 101 | 
            +
                            for p in re.split(r"[,;]|\band\b", pollutants_str)
         | 
| 102 | 
            +
                            if p.strip().lower() in self.pollutants
         | 
| 103 | 
            +
                        ]
         | 
| 104 | 
            +
             | 
| 105 | 
            +
                    # Extract severity
         | 
| 106 | 
            +
                    severity_match = re.search(r"(?i)(severity|level)[:\s]*(\d{1,2})", analysis)
         | 
| 107 | 
            +
             | 
| 108 | 
            +
                    if severity_match:
         | 
| 109 | 
            +
                        try:
         | 
| 110 | 
            +
                            severity = min(max(int(severity_match.group(2)), 1), 10)
         | 
| 111 | 
            +
                        except:
         | 
| 112 | 
            +
                            severity = self._calculate_severity(pollutants)
         | 
| 113 | 
            +
                    else:
         | 
| 114 | 
            +
                        severity = self._calculate_severity(pollutants)
         | 
| 115 | 
            +
             | 
| 116 | 
            +
                    return pollutants, severity
         | 
| 117 | 
            +
             | 
| 118 | 
            +
                def _calculate_severity(self, pollutants: List[str]) -> int:
         | 
| 119 | 
            +
                    """Weighted severity calculation"""
         | 
| 120 | 
            +
                    if not pollutants:
         | 
| 121 | 
            +
                        return 1
         | 
| 122 | 
            +
             | 
| 123 | 
            +
                    weights = {
         | 
| 124 | 
            +
                        "medical waste": 3,
         | 
| 125 | 
            +
                        "toxic sludge": 3,
         | 
| 126 | 
            +
                        "oil spill": 2.5,
         | 
| 127 | 
            +
                        "chemical foam": 2,
         | 
| 128 | 
            +
                        "industrial discharge": 2,
         | 
| 129 | 
            +
                        "sewage water": 2,
         | 
| 130 | 
            +
                        "plastic waste": 1.5,
         | 
| 131 | 
            +
                        "construction waste": 1.5,
         | 
| 132 | 
            +
                        "algal bloom": 1.5,
         | 
| 133 | 
            +
                        "agricultural runoff": 1.5,
         | 
| 134 | 
            +
                        "floating trash": 1,
         | 
| 135 | 
            +
                        "organic debris": 1,
         | 
| 136 | 
            +
                    }
         | 
| 137 | 
            +
             | 
| 138 | 
            +
                    avg_weight = sum(weights.get(p, 1) for p in pollutants) / len(pollutants)
         | 
| 139 | 
            +
                    return min(10, max(1, round(avg_weight * 3)))
         | 
| 140 | 
            +
             | 
| 141 | 
            +
                def _format_analysis(self, pollutants: List[str], severity: int) -> str:
         | 
| 142 | 
            +
                    """Generate formatted report"""
         | 
| 143 | 
            +
                    severity_bar = f"""π Severity: {severity}/10
         | 
| 144 | 
            +
            {"β" * severity}{"β" * (10 - severity)}
         | 
| 145 | 
            +
            {self.severity_descriptions.get(severity, "")}"""
         | 
| 146 | 
            +
             | 
| 147 | 
            +
                    pollutants_list = (
         | 
| 148 | 
            +
                        "\nπ No pollutants detected"
         | 
| 149 | 
            +
                        if not pollutants
         | 
| 150 | 
            +
                        else "\n".join(
         | 
| 151 | 
            +
                            f"{i}. {p.capitalize()}" for i, p in enumerate(pollutants[:5], 1)
         | 
| 152 | 
            +
                        )
         | 
| 153 | 
            +
                    )
         | 
| 154 | 
            +
             | 
| 155 | 
            +
                    return f"""π River Pollution Analysis π
         | 
| 156 | 
            +
            {pollutants_list}
         | 
| 157 | 
            +
            {severity_bar}"""
         | 
| 158 | 
            +
             | 
| 159 | 
            +
                def analyze_chat(self, message: str) -> str:
         | 
| 160 | 
            +
                    """Handle chat questions about pollution"""
         | 
| 161 | 
            +
                    # Simple implementation - you can expand this
         | 
| 162 | 
            +
                    if any(word in message.lower() for word in ["hello", "hi", "hey"]):
         | 
| 163 | 
            +
                        return "Hello! I'm a river pollution analyzer. Ask me about pollution types or upload an image for analysis."
         | 
| 164 | 
            +
                    elif "pollution" in message.lower():
         | 
| 165 | 
            +
                        return "Common river pollutants include: plastic waste, chemical foam, industrial discharge, sewage water, and oil spills."
         | 
| 166 | 
            +
                    else:
         | 
| 167 | 
            +
                        return "I can answer questions about river pollution. Try asking about pollution types or upload an image for analysis."
         | 
| 168 | 
            +
             | 
| 169 | 
            +
             | 
| 170 | 
            +
            # Initialize analyzer
         | 
| 171 | 
            +
            analyzer = RiverPollutionAnalyzer()
         | 
| 172 | 
            +
             | 
| 173 | 
            +
            css = """
         | 
| 174 | 
            +
            .header {
         | 
| 175 | 
            +
                text-align: center;
         | 
| 176 | 
            +
                padding: 20px;
         | 
| 177 | 
            +
                background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
         | 
| 178 | 
            +
                border-radius: 10px;
         | 
| 179 | 
            +
                margin-bottom: 20px;
         | 
| 180 | 
            +
            }
         | 
| 181 | 
            +
             | 
| 182 | 
            +
            .side-by-side {
         | 
| 183 | 
            +
                display: flex;
         | 
| 184 | 
            +
                gap: 20px;
         | 
| 185 | 
            +
            }
         | 
| 186 | 
            +
             | 
| 187 | 
            +
            .left-panel, .right-panel {
         | 
| 188 | 
            +
                flex: 1;
         | 
| 189 | 
            +
            }
         | 
| 190 | 
            +
             | 
| 191 | 
            +
            .analysis-box {
         | 
| 192 | 
            +
                padding: 20px;
         | 
| 193 | 
            +
                background: #f8f9fa;
         | 
| 194 | 
            +
                border-radius: 10px;
         | 
| 195 | 
            +
                margin-top: 20px;
         | 
| 196 | 
            +
                border: 1px solid #dee2e6;
         | 
| 197 | 
            +
            }
         | 
| 198 | 
            +
             | 
| 199 | 
            +
            .chat-container {
         | 
| 200 | 
            +
                background: #f8f9fa;
         | 
| 201 | 
            +
                padding: 20px;
         | 
| 202 | 
            +
                border-radius: 10px;
         | 
| 203 | 
            +
                height: 100%;
         | 
| 204 | 
            +
            }
         | 
| 205 | 
            +
            """
         | 
| 206 | 
            +
             | 
| 207 | 
            +
            with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
         | 
| 208 | 
            +
                with gr.Column(elem_classes="header"):
         | 
| 209 | 
            +
                    gr.Markdown("# π River Pollution Analyzer")
         | 
| 210 | 
            +
                    gr.Markdown("### AI-powered water pollution detection")
         | 
| 211 | 
            +
             | 
| 212 | 
            +
                with gr.Row(elem_classes="side-by-side"):
         | 
| 213 | 
            +
                    # Left Panel
         | 
| 214 | 
            +
                    with gr.Column(elem_classes="left-panel"):
         | 
| 215 | 
            +
                        with gr.Group():
         | 
| 216 | 
            +
                            image_input = gr.Image(
         | 
| 217 | 
            +
                                type="pil", label="Upload River Image", height=300
         | 
| 218 | 
            +
                            )
         | 
| 219 | 
            +
                            analyze_btn = gr.Button("π Analyze Pollution", variant="primary")
         | 
| 220 | 
            +
             | 
| 221 | 
            +
                        with gr.Group(elem_classes="analysis-box"):
         | 
| 222 | 
            +
                            gr.Markdown("### π Analysis report")
         | 
| 223 | 
            +
                            analysis_output = gr.Markdown()
         | 
| 224 | 
            +
             | 
| 225 | 
            +
                    # Right Panel
         | 
| 226 | 
            +
                    with gr.Column(elem_classes="right-panel"):
         | 
| 227 | 
            +
                        with gr.Group(elem_classes="chat-container"):
         | 
| 228 | 
            +
                            chatbot = gr.Chatbot(label="Pollution Analysis Q&A", height=400)
         | 
| 229 | 
            +
                            with gr.Row():
         | 
| 230 | 
            +
                                chat_input = gr.Textbox(
         | 
| 231 | 
            +
                                    placeholder="Ask about pollution sources...",
         | 
| 232 | 
            +
                                    label="Your Question",
         | 
| 233 | 
            +
                                    container=False,
         | 
| 234 | 
            +
                                    scale=5,
         | 
| 235 | 
            +
                                )
         | 
| 236 | 
            +
                                chat_btn = gr.Button("π¬ Ask", variant="secondary", scale=1)
         | 
| 237 | 
            +
                            clear_btn = gr.Button("π§Ή Clear Chat History", size="sm")
         | 
| 238 | 
            +
             | 
| 239 | 
            +
                analyze_btn.click(
         | 
| 240 | 
            +
                    analyzer.analyze_image, inputs=image_input, outputs=analysis_output
         | 
| 241 | 
            +
                )
         | 
| 242 | 
            +
             | 
| 243 | 
            +
                chat_input.submit(
         | 
| 244 | 
            +
                    lambda msg, chat: ("", chat + [(msg, analyzer.analyze_chat(msg))]),
         | 
| 245 | 
            +
                    inputs=[chat_input, chatbot],
         | 
| 246 | 
            +
                    outputs=[chat_input, chatbot],
         | 
| 247 | 
            +
                )
         | 
| 248 | 
            +
             | 
| 249 | 
            +
                chat_btn.click(
         | 
| 250 | 
            +
                    lambda msg, chat: ("", chat + [(msg, analyzer.analyze_chat(msg))]),
         | 
| 251 | 
            +
                    inputs=[chat_input, chatbot],
         | 
| 252 | 
            +
                    outputs=[chat_input, chatbot],
         | 
| 253 | 
            +
                )
         | 
| 254 | 
            +
             | 
| 255 | 
            +
                clear_btn.click(lambda: None, outputs=[chatbot])
         | 
| 256 | 
            +
             | 
| 257 | 
            +
                gr.Examples(
         | 
| 258 | 
            +
                    examples=[
         | 
| 259 | 
            +
                        [
         | 
| 260 | 
            +
                            "https://huggingface.co/spaces/username/your-space-name/resolve/main/examples/polluted_river_1.jpg"
         | 
| 261 | 
            +
                        ],
         | 
| 262 | 
            +
                        [
         | 
| 263 | 
            +
                            "https://huggingface.co/spaces/username/your-space-name/resolve/main/examples/polluted_river_2.jpg"
         | 
| 264 | 
            +
                        ],
         | 
| 265 | 
            +
                    ],
         | 
| 266 | 
            +
                    inputs=image_input,
         | 
| 267 | 
            +
                    outputs=analysis_output,
         | 
| 268 | 
            +
                    fn=analyzer.analyze_image,
         | 
| 269 | 
            +
                    cache_examples=True,
         | 
| 270 | 
            +
                    label="Try example images:",
         | 
| 271 | 
            +
                )
         | 
| 272 | 
            +
             | 
| 273 | 
            +
            demo.launch()
         | 
    	
        polluted_river1.jpg
    ADDED
    
    |   | 
    	
        polluted_river2.jpg
    ADDED
    
    |   | 
    	
        requirements.txt
    ADDED
    
    | @@ -0,0 +1,6 @@ | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | 
|  | |
| 1 | 
            +
            transformers>=4.35.0
         | 
| 2 | 
            +
            accelerate>=0.24.0
         | 
| 3 | 
            +
            bitsandbytes>=0.41.0
         | 
| 4 | 
            +
            gradio>=3.50.0
         | 
| 5 | 
            +
            torch>=2.0.0
         | 
| 6 | 
            +
            pillow>=10.0.0
         |