Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import os | |
| from groq import Groq | |
| # Initialize Groq client | |
| client = Groq(api_key=os.environ.get("CHATAPI")) | |
| def calculate_carbon_footprint(energy_consumption, transportation_km, waste_production, water_usage, food_choices): | |
| try: | |
| # Calculate carbon footprint | |
| carbon_footprint = ( | |
| energy_consumption * 0.5 + | |
| transportation_km * 0.15 + | |
| waste_production * 0.66 + | |
| water_usage * 0.027 + | |
| {"Meat-heavy": 2.0, "Balanced": 1.5, "Vegetarian": 1.0, "Vegan": 0.5}[food_choices] | |
| ) | |
| # Add randomness for realism | |
| carbon_footprint *= random.uniform(0.9, 1.1) | |
| # Calculate number of trees needed for offset | |
| trees_needed = round(carbon_footprint * 1000 / 22) | |
| # Create the message for the language model | |
| message = ( | |
| f"Your estimated carbon footprint is {carbon_footprint:.2f} tons of CO2 per year.\n\n" | |
| f"To offset this and reach net zero, you would need to plant approximately {trees_needed} trees.\n\n" | |
| "Note: This is a simplified calculation. Actual values may vary based on more detailed factors." | |
| ) | |
| # Get a response from the language model | |
| chat_completion = client.chat.completions.create( | |
| messages=[ | |
| { | |
| "role": "user", | |
| "content": message, | |
| } | |
| ], | |
| model="llama3-8b-instant" # Replace with the correct model identifier | |
| ) | |
| result = chat_completion['choices'][0]['message']['content'] | |
| return result | |
| except KeyError as e: | |
| return f"An invalid food choice was selected: {str(e)}" | |
| except Exception as e: | |
| return f"An error occurred: {str(e)}" | |
| iface = gr.Interface( | |
| fn=calculate_carbon_footprint, | |
| inputs=[ | |
| gr.Slider(0, 1000, step=1, label="Energy Consumption (kWh/month)"), | |
| gr.Slider(0, 50000, step=1, label="Transportation (km/year)"), | |
| gr.Slider(0, 50, step=1, label="Waste Production (kg/week)"), | |
| gr.Slider(0, 1000, step=1, label="Water Usage (liters/day)"), | |
| gr.Radio(["Meat-heavy", "Balanced", "Vegetarian", "Vegan"], label="Food Choices") | |
| ], | |
| outputs="text", | |
| title="Carbon Footprint Calculator with Language Model", | |
| description="Enter your usage details to get a detailed analysis of your carbon footprint and offset requirements." | |
| ) | |
| iface.launch() | |