@@ -30,35 +30,35 @@ def process_energy_file(file_path):
3030 try :
3131 with open (file_path , 'r' ) as f :
3232 content = f .read ()
33-
33+
3434 # Parse JSON with schema validation
3535 bill_data = json .loads (content )
36-
36+
3737 if not isinstance (bill_data , dict ):
3838 raise ValueError ("Invalid JSON structure - expected dictionary" )
39-
39+
4040 # Extract required fields
4141 fields = bill_data .get ("bill_structure" , {}).get ("fields" , {})
4242 if "total_kWh" not in fields :
4343 raise ValueError ("Missing required total_kWh field" )
44-
44+
4545 # Convert string values to actual numbers
4646 try :
4747 kwh = float (fields ["total_kWh" ])
4848 except (ValueError , TypeError ):
4949 raise ValueError ("total_kWh must be a numeric value" )
50-
50+
5151 # Extract additional context
5252 metadata = {
5353 'tariff_type' : fields .get ("tariff_type" , "Unknown" ),
5454 'location_type' : fields .get ("location_type" , "Unknown" ),
5555 'billing_period' : fields .get ("billing_period" , "Unknown" ),
5656 'source' : bill_data .get ("source" , "Unknown provider" )
5757 }
58-
58+
5959 # Get interpretation rules
6060 rules = bill_data .get ("interpretation_rules" , {})
61-
61+
6262 return {
6363 'timestamp' : datetime .now ().strftime ("%Y-%m-%d %H:%M:%S" ),
6464 'kwh' : kwh ,
@@ -68,12 +68,31 @@ def process_energy_file(file_path):
6868 'optimizations' : bill_data .get ("optimization_suggestions" , {}),
6969 'units' : bill_data .get ("units" , {})
7070 }
71-
71+
7272 except json .JSONDecodeError :
7373 raise ValueError ("Invalid JSON format" )
7474 except Exception as e :
7575 print (f"File processing error: { str (e )} " )
7676 return None
77+ # ... [previous code remains the same] ...
78+
79+ def generate_response (user_prompt ):
80+ """Generate AI response with error handling and content filtering"""
81+ try :
82+ response = client .chat .completions .create (
83+ model = deployment ,
84+ messages = [
85+ {"role" : "system" , "content" : SYSTEM_PROMPT },
86+ {"role" : "user" , "content" : user_prompt }
87+ ],
88+ temperature = 0.7 ,
89+ max_tokens = 1000
90+ )
91+ return response .choices [0 ].message .content
92+
93+ except Exception as e :
94+ print (f"API Error: { str (e )} " )
95+ return CONTENT_FILTER_MESSAGE
7796
7897def handle_energy_bill ():
7998 """Enhanced energy analysis for Egyptian bills"""
@@ -96,7 +115,7 @@ def handle_energy_bill():
96115 - Location: { bill_data ['metadata' ]['location_type' ]}
97116 - Billing Period: { bill_data ['metadata' ]['billing_period' ]}
98117 - Emissions Factor: { bill_data ['units' ].get ('emissions_estimate_factor' , '0.55 kg CO2/kWh (Egypt default)' )}
99-
118+
100119 Industry Benchmarks:
101120 - Night Usage Threshold: { bill_data ['rules' ].get ('night_usage_threshold' , 0.2 )}
102121 - Average kWh/10k sqft: { bill_data ['rules' ].get ('industry_average_kWh_per_10000_sqft' , 12250 )}
@@ -106,7 +125,7 @@ def handle_energy_bill():
106125 { context }
107126 - Usage: { bill_data ['kwh' ]} kWh
108127 - Date Processed: { bill_data ['timestamp' ]}
109-
128+
110129 Provide:
111130 1. CO2e calculation using Egyptian grid factor
112131 2. Comparison to EEHC regional benchmarks
@@ -115,13 +134,30 @@ def handle_energy_bill():
115134 - { bill_data ['metadata' ]['location_type' ]} location factors
116135 - Time-of-use patterns
117136 4. Flag any usage anomalies per EEHC standards
118-
119- Format with markdown tables and Egyptian-specific examples."""
120137
121- bill_analysis = generate_response (analysis_prompt )
122- return bill_analysis if bill_analysis != CONTENT_FILTER_MESSAGE else "Analysis blocked"
138+ Format with markdown tables and Egyptian-specific examples."""
139+ bill_analysis = generate_response (analysis_prompt ) # Now properly defined return bill_analysis if bill_analysis != CONTENT_FILTER_MESSAGE else "Analysis blocked"def handle_sustainability_goal():
140+ """Configure sustainability scope with validation"""
141+ global current_scope
142+ print ("Available Scopes:" )
143+ print ("1. Scope 1 (Direct emissions)" )
144+ print ("2. Scope 2 (Electricity indirect emissions)" )
145+ print ("3. Scope 3 (Value chain emissions)" )
146+
147+ choice = input ("Select scope (1-3): " ).strip ()
148+ scope_map = {
149+ "1" : "Scope 1 - Direct Emissions" ,
150+ "2" : "Scope 2 - Electricity Indirect" ,
151+ "3" : "Scope 3 - Value Chain"
152+ }
153+
154+ if choice in scope_map :
155+ current_scope = scope_map [choice ]
156+ return f"Scope set to: { current_scope } "
157+ else :
158+ current_scope = "Not Specified"
159+ return "Invalid scope selection - using default analysis"
123160
124- # ... [rest of your original code remains the same] ...
125161
126162def handle_recommendations ():
127163 """Recommendation generation"""
@@ -138,11 +174,23 @@ def handle_recommendations():
138174 response = generate_response (recommendation_prompt )
139175 return response if response != CONTENT_FILTER_MESSAGE else "Recommendation blocked"
140176
177+
178+
179+
180+ def display_menu ():
181+ """Display main menu and get user choice"""
182+ print ("\n Main Menu:" )
183+ print ("1. Configure Sustainability Scope" )
184+ print ("2. Analyze Energy Bill" )
185+ print ("3. Generate Recommendations" )
186+ print ("4. Exit" )
187+ return input ("Please select an option (1-4): " ).strip ()
188+
141189def main ():
142190 print ("Welcome to Carbon Footprint Analysis" )
143191 print (f"AI Model: { model_name } | API: { api_version } " )
144192 while True :
145- choice = display_menu ()
193+ choice = display_menu () # Now properly defined
146194 if choice == "1" :
147195 print ("\n === Scope Configuration ===" )
148196 print (handle_sustainability_goal ())
0 commit comments