File size: 14,833 Bytes
86675d2
4f206b9
1369577
4f206b9
 
 
 
6a66e6f
1369577
4f206b9
 
 
 
 
 
 
1369577
 
4f206b9
1369577
 
4f206b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1369577
4f206b9
7b791f9
 
 
 
 
 
 
 
 
 
 
 
 
 
45561c6
7b791f9
 
 
 
 
 
1369577
 
4f206b9
 
 
 
 
 
e6f8836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ec6adc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f206b9
 
 
 
 
bc8a428
7b791f9
4f206b9
3ce2003
4f206b9
 
bc8a428
 
7b791f9
bc8a428
 
 
 
 
 
4f206b9
 
3ce2003
 
 
 
 
 
4f206b9
 
bc8a428
7b791f9
4f206b9
3ce2003
4f206b9
 
bc8a428
 
7b791f9
bc8a428
 
 
 
 
 
4f206b9
 
 
3ce2003
 
 
 
 
 
4f206b9
bc8a428
4f206b9
 
 
 
7b791f9
4f206b9
3ce2003
4f206b9
 
bc8a428
 
7b791f9
bc8a428
 
 
 
 
 
4f206b9
 
 
3ce2003
 
 
 
 
 
4f206b9
bc8a428
4f206b9
 
 
 
7b791f9
4f206b9
3ce2003
4f206b9
 
bc8a428
 
7b791f9
bc8a428
 
 
 
 
 
4f206b9
 
3ce2003
 
 
 
 
 
4f206b9
 
 
 
 
 
 
 
 
 
 
 
1369577
4f206b9
 
3ce2003
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import gradio as gr
import os
from openai import OpenAI
import requests
from PIL import Image
import io
import tempfile
import base64

def analyze_environmental_impact(api_key, analysis_type, image=None, text_input=None, location=None, product_info=None):
    """
    Analyze environmental impact based on user inputs using Gemini 2.5 Pro through OpenRouter.
    """
    if not api_key:
        return "Please provide an OpenRouter API key."
    
    client = OpenAI(
        base_url="https://openrouter.ai/api/v1",
        api_key=api_key,
    )
    
    # Prepare messages based on analysis type
    if analysis_type == "Image Analysis":
        if image is None:
            return "Please upload an image for analysis."
            
        # Save image to a temporary file
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg")
        image_path = temp_file.name
        image.save(image_path)
        
        # Convert image to base64
        with open(image_path, "rb") as img_file:
            image_base64 = base64.b64encode(img_file.read()).decode("utf-8")
        
        # Clean up temp file
        os.unlink(image_path)
        
        prompt = """
        Analyze this image for environmental impact factors. Consider:
        1. Visible ecosystems, wildlife, or natural resources
        2. Human infrastructure and its potential environmental footprint
        3. Evidence of pollution, waste, or environmental degradation
        4. Sustainable or eco-friendly elements
        
        Provide a comprehensive environmental impact assessment and suggest ways to improve 
        sustainability based on what you see.
        """
        
        messages = [
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": prompt
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": f"data:image/jpeg;base64,{image_base64}"
                        }
                    }
                ]
            }
        ]
        
    elif analysis_type == "Geographical Assessment":
        if not location:
            return "Please provide a location for geographical assessment."
        
        prompt = f"""
        Provide an environmental impact assessment for the location: {location}.
        
        Include information about:
        1. Current environmental conditions (air quality, water resources, biodiversity)
        2. Major environmental challenges and threats
        3. Sustainability initiatives and progress
        4. Carbon footprint and emissions data
        5. Recommendations for improving environmental sustainability in this area
        
        Present the information in a structured format with clear sections for each aspect.
        """
        
        messages = [
            {
                "role": "user",
                "content": prompt
            }
        ]
        
    elif analysis_type == "Product Assessment":
        if not product_info:
            return "Please provide product information for assessment."
        
        prompt = f"""
        Analyze the environmental impact of the following product:
        
        {product_info}
        
        Include in your assessment:
        1. Materials and resources used
        2. Manufacturing process impact
        3. Transportation and distribution footprint
        4. Usage phase environmental impact
        5. End-of-life considerations
        6. Overall sustainability score on a scale of 1-10
        7. Recommendations for improving the product's environmental footprint
        
        Be specific and provide actionable insights.
        """
        
        messages = [
            {
                "role": "user",
                "content": prompt
            }
        ]
        
    elif analysis_type == "Custom Query":
        if not text_input:
            return "Please provide a query for custom environmental analysis."
        
        prompt = f"""
        Provide an environmental impact analysis based on the following information:
        
        {text_input}
        
        Include in your response:
        1. Key environmental concerns identified
        2. Potential ecological impacts - short and long term
        3. Carbon footprint considerations
        4. Waste and pollution factors
        5. Biodiversity impacts
        6. Actionable recommendations for sustainability
        7. References to relevant environmental principles or frameworks
        
        Be specific, thorough, and provide practical advice.
        """
        
        messages = [
            {
                "role": "user",
                "content": prompt
            }
        ]
    
    # Make API call
    try:
        completion = client.chat.completions.create(
            extra_headers={
                "HTTP-Referer": "https://environmental-impact-analyzer.app",
                "X-Title": "Smart Environmental Impact Analyzer",
            },
            model="google/gemini-2.5-pro-exp-03-25:free",
            messages=messages
        )
        
        # Check if completion and choices exist before accessing
        if completion and hasattr(completion, 'choices') and completion.choices and len(completion.choices) > 0:
            if hasattr(completion.choices[0], 'message') and completion.choices[0].message:
                return completion.choices[0].message.content
            else:
                return "Error: Received empty message from API."
        else:
            return "Error: Received incomplete response from API."
            
    except Exception as e:
        return f"Error during analysis: {str(e)}"

# Create Gradio interface
with gr.Blocks(title="Smart Environmental Impact Analyzer") as app:
    gr.Markdown("# 🌍 Smart Environmental Impact Analyzer")
    gr.Markdown("""
    This tool analyzes environmental impacts using Gemini 2.5 Pro AI. 
    Choose an analysis type and provide the required information.
    """)

    with gr.Accordion("Sample Example Inputs", open=False):
        gr.Markdown("""
        ### API Key Input:
        First, you'll need an OpenRouter API key. If you don't have one, you can get it from [openrouter.ai](https://openrouter.ai). This should be entered in the "OpenRouter API Key" field.
        Sample API key format (not a real key): 
        ```
        sk-or-v1-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        ```

        ### Image Analysis Tab:
        Upload an image like:
        - A cityscape with visible pollution
        - A forest or natural area
        - An industrial facility
        - A solar farm or wind turbines
        - A beach with visible plastic waste

        For testing purposes, you could use public domain environmental images from sites like [Unsplash](https://unsplash.com) or [Pexels](https://www.pexels.com).

        ### Geographical Assessment Tab:
        Sample location inputs:
        - **New York City, USA**
        - **Copenhagen, Denmark**
        - **Amazon Rainforest, Brazil**
        - **Great Barrier Reef, Australia**

        ### Product Assessment Tab:
        Sample product descriptions:
        1. **Plastic water bottle** made from PET plastic. Single-use design with a plastic cap. Manufactured in China and shipped globally. Typical lifecycle includes production, distribution, single use, and disposal, with most bottles ending up in landfills or as litter.
        2. **Electric car** with a 75kWh lithium-ion battery. Aluminum and steel body with leather interior. Manufactured in California, USA. Average lifespan of 15 years or 200,000 miles. Battery requires rare earth minerals from mining operations.
        3. **Organic cotton t-shirt**, grown without pesticides or synthetic fertilizers. Made in India using natural dyes. Packaged in recycled paper. Designed to last approximately 50 washes.

        ### Custom Query Tab:
        Sample queries:
        1. What is the environmental impact of bitcoin mining and cryptocurrency operations? How does it compare to traditional banking systems?
        2. How would switching to a plant-based diet for one year affect my personal carbon footprint? What specific food choices would have the biggest positive impact?
        3. What are the environmental trade-offs between paper packaging and plastic packaging for food products? When is each option more sustainable?
        4. How does fast fashion impact water resources? What sustainable alternatives exist?
        """)

    with gr.Accordion("About the project!", open=False):
        gr.Markdown("""
        ### Image Analysis:
        Users can upload an image to analyze environmental impacts, such as:
        - Pollution
        - Ecosystems
        - Human infrastructure
        
        ### Geographical Assessment:
        This section allows users to input a location and receive an analysis of:
        - Environmental conditions
        - Challenges
        - Sustainability efforts
        
        ### Product Assessment:
        Users can input product details to analyze the environmental impact throughout the product’s lifecycle, including:
        - Materials used
        - Manufacturing process
        - Disposal
        
        ### Custom Query:
        This section allows users to input any custom environmental query to receive a detailed analysis, covering:
        - Carbon footprint
        - Waste and pollution
        - Sustainability practices
        """)
    
    api_key = gr.Textbox(label="OpenRouter API Key", placeholder="Enter your OpenRouter API key", type="password")
    
    with gr.Tabs():
        with gr.TabItem("Image Analysis"):
            image_input = gr.Image(type="pil", label="Upload an image for environmental analysis")
            image_submit = gr.Button("Analyze Image")
            image_output = gr.Textbox(label="Analysis Results", lines=15)
            image_clear = gr.Button("Clear Response")
            
            image_submit.click(
                analyze_environmental_impact,
                inputs=[
                    api_key,  # Directly pass the api_key component
                    gr.Textbox(value="Image Analysis", visible=False),
                    image_input,
                    gr.Textbox(value="", visible=False),
                    gr.Textbox(value="", visible=False),
                    gr.Textbox(value="", visible=False)
                ],
                outputs=image_output
            )
            
            image_clear.click(
                lambda: "",
                inputs=[],
                outputs=image_output
            )
        
        with gr.TabItem("Geographical Assessment"):
            location_input = gr.Textbox(label="Location (city, region, or country)", placeholder="e.g., Paris, France")
            location_submit = gr.Button("Analyze Location")
            location_output = gr.Textbox(label="Analysis Results", lines=15)
            location_clear = gr.Button("Clear Response")
            
            location_submit.click(
                analyze_environmental_impact,
                inputs=[
                    api_key,  # Directly pass the api_key component
                    gr.Textbox(value="Geographical Assessment", visible=False),
                    gr.Image(value=None, visible=False, type="pil"),
                    gr.Textbox(value="", visible=False),
                    location_input,
                    gr.Textbox(value="", visible=False)
                ],
                outputs=location_output
            )
            
            location_clear.click(
                lambda: "",
                inputs=[],
                outputs=location_output
            )
            
        with gr.TabItem("Product Assessment"):
            product_info = gr.Textbox(
                label="Product Information", 
                placeholder="Describe the product, materials, manufacturing process, lifecycle, etc.",
                lines=5
            )
            product_submit = gr.Button("Analyze Product")
            product_output = gr.Textbox(label="Analysis Results", lines=15)
            product_clear = gr.Button("Clear Response")
            
            product_submit.click(
                analyze_environmental_impact,
                inputs=[
                    api_key,  # Directly pass the api_key component
                    gr.Textbox(value="Product Assessment", visible=False),
                    gr.Image(value=None, visible=False, type="pil"),
                    gr.Textbox(value="", visible=False),
                    gr.Textbox(value="", visible=False),
                    product_info
                ],
                outputs=product_output
            )
            
            product_clear.click(
                lambda: "",
                inputs=[],
                outputs=product_output
            )
            
        with gr.TabItem("Custom Query"):
            custom_input = gr.Textbox(
                label="Custom Environmental Query",
                placeholder="Enter your environmental question or describe a scenario to analyze",
                lines=5
            )
            custom_submit = gr.Button("Analyze")
            custom_output = gr.Textbox(label="Analysis Results", lines=15)
            custom_clear = gr.Button("Clear Response")
            
            custom_submit.click(
                analyze_environmental_impact,
                inputs=[
                    api_key,  # Directly pass the api_key component
                    gr.Textbox(value="Custom Query", visible=False),
                    gr.Image(value=None, visible=False, type="pil"),
                    custom_input,
                    gr.Textbox(value="", visible=False),
                    gr.Textbox(value="", visible=False)
                ],
                outputs=custom_output
            )
            
            custom_clear.click(
                lambda: "",
                inputs=[],
                outputs=custom_output
            )
    
    gr.Markdown("""
    ### Privacy Notice
    Your API key is used only for making requests to OpenRouter and is not stored or logged.
    The images and text you submit are processed by Gemini 2.5 Pro through OpenRouter's API.
    
    ### Usage Instructions
    1. Enter your OpenRouter API key (get one from https://openrouter.ai)
    2. Select the type of analysis you want to perform
    3. Provide the required information (image, location, product details, or custom query)
    4. Click the "Analyze" button for your selected tab
    """)

# Launch the app
if __name__ == "__main__":
    app.launch()