File size: 5,806 Bytes
7ebf747
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42c47cc
7ebf747
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42c47cc
7ebf747
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42c47cc
 
 
 
 
7ebf747
 
 
 
 
 
 
 
 
 
 
 
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
#gradio app

import gradio as gr
import json
from Agent import create_environmental_analyzer

def analyze_environmental_impact(product_description):
    """Main analysis function that processes input and returns formatted results"""
    
    if not product_description.strip():
        return "Please enter a product description to analyze.", "", "", ""
    
    # Initialize the analyzer
    analyzer = create_environmental_analyzer()
    
    # Run the analysis
    initial_state = {
        "messages": [],
        "product_description": product_description,
        "extracted_data": {},
        "carbon_footprint": 0.0,
        "environmental_score": 0.0,
        "recommendations": [],
        "analysis_complete": False
    }
    
    # Process through the workflow
    final_state = analyzer.invoke(initial_state)
    
    # Format results for display
    score_display, status_message, details_json, recommendations_text = format_results(final_state)
    
    return score_display, status_message, details_json, recommendations_text

def format_results(state):
    """Format the analysis results for Gradio display"""
    
    # Environmental Score Display
    score = state['environmental_score']
    carbon = state['carbon_footprint']
    
    score_display = f"""
    ## Environmental Impact Score
    
    **Score: {score}/100**
    
    **Carbon Footprint: {carbon:.2f} kg CO2e**
    """
    
    # Status Message based on score
    if score >= 80:
        status_message = "🌟 **Excellent environmental performance!**\n\nThis product demonstrates outstanding sustainability practices."
    elif score >= 60:
        status_message = "⚡ **Good, but room for improvement**\n\nThis product has decent environmental performance with potential for enhancement."
    else:
        status_message = "🚨 **High environmental impact**\n\nThis product has significant environmental concerns that should be addressed."
    
    # Analysis Details as JSON
    details_json = state['extracted_data']
    
    # Recommendations as formatted text
    recommendations_text = "## Sustainability Recommendations\n\n"
    if state['recommendations']:
        for i, rec in enumerate(state['recommendations'], 1):
            recommendations_text += f"{i}. {rec}\n\n"
    else:
        recommendations_text += "No specific recommendations available."
    
    return score_display, status_message, details_json, recommendations_text

def create_gradio_interface():
    """Create the Gradio interface"""
    
    with gr.Blocks(
        title="🌱 AI Environmental Impact Analyzer",
        theme=gr.themes.Soft()
    ) as interface:
        
        # Header
        gr.Markdown("# 🌱 AI Environmental Impact Analyzer")
        gr.Markdown("Analyze the environmental footprint of consumer products using AI")
        
        with gr.Row():
            with gr.Column(scale=2):
                # Input section
                product_input = gr.Textbox(
                    label="Product Description/URL",
                    placeholder="e.g., Organic cotton t-shirt manufactured in India, packaged in recyclable materials...",
                    lines=4,
                    max_lines=8
                )
                
                analyze_btn = gr.Button(
                    "🔍 Analyze Environmental Impact",
                    variant="primary",
                    size="lg"
                )
            
            with gr.Column(scale=3):
                # Results section
                with gr.Group():
                    score_output = gr.Markdown(
                        label="Environmental Score",
                        value="Enter a product description/URL and click analyze to see results."
                    )
                    
                    status_output = gr.Markdown(
                        label="Performance Status"
                    )
        
        # Detailed results in tabs
        with gr.Tabs():
            with gr.Tab("📊 Analysis Details"):
                details_output = gr.JSON(
                    label="Extracted Environmental Data",
                    value={}
                )
            
            with gr.Tab("💡 Recommendations"):
                recommendations_output = gr.Markdown(
                    label="Sustainability Recommendations",
                    value="Analysis results will appear here..."
                )
        
        # Event handlers
        analyze_btn.click(
            fn=analyze_environmental_impact,
            inputs=[product_input],
            outputs=[score_output, status_output, details_output, recommendations_output],
            show_progress=True
        )
        
        # Optional: Add examples
        gr.Examples(
            examples=[
                ["Organic cotton t-shirt manufactured in India, packaged in recyclable cardboard"],
                ["Plastic water bottle made from recycled materials, shipped internationally"],
                ["Local handmade wooden furniture using sustainable forest wood"],
                ["Electronic smartphone with aluminum body, manufactured in China"]
            ],
            inputs=[product_input],
            label="Example Products to Analyze"
        )
        gr.Markdown("""
        **Note**: add the Following Secret Key to your environment variables:
                    - `HF_API_KEY` (Hugging Face API token) to access private models or higher rate limits.
                    - `CLIMATIQ_API_KEY` (Climatiq API token) for carbon footprint calculations.
                    """)
    
    return interface

def main():
    """Launch the Gradio application"""
    interface = create_gradio_interface()
    
    # Launch with custom settings
    interface.launch()

if __name__ == "__main__":
    main()