import gradio as gr import os from openai import OpenAI import requests from PIL import Image import io import tempfile 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: import base64 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", # Replace with your actual site "X-Title": "Smart Environmental Impact Analyzer", }, model="google/gemini-2.5-pro-exp-03-25:free", messages=messages ) return completion.choices[0].message.content 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. """) api_key = gr.Textbox(label="OpenRouter API Key", placeholder="Enter your OpenRouter API key", type="password") # Create hidden inputs for each tab with gr.Group(visible=False) as hidden_inputs: analysis_type_input = gr.Textbox(value="Image Analysis", visible=False) empty_text_input = gr.Textbox(value="", visible=False) empty_location_input = gr.Textbox(value="", visible=False) empty_product_input = gr.Textbox(value="", visible=False) 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_submit.click( analyze_environmental_impact, inputs=[ api_key, gr.Textbox(value="Image Analysis", visible=False), image_input, empty_text_input, empty_location_input, empty_product_input ], 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_submit.click( analyze_environmental_impact, inputs=[ api_key, gr.Textbox(value="Geographical Assessment", visible=False), gr.Image(visible=False, type="pil"), empty_text_input, location_input, empty_product_input ], 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_submit.click( analyze_environmental_impact, inputs=[ api_key, gr.Textbox(value="Product Assessment", visible=False), gr.Image(visible=False, type="pil"), empty_text_input, empty_location_input, product_info ], 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_submit.click( analyze_environmental_impact, inputs=[ api_key, gr.Textbox(value="Custom Query", visible=False), gr.Image(visible=False, type="pil"), custom_input, empty_location_input, empty_product_input ], 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()