tamizh-me commited on
Commit
5245224
·
verified ·
1 Parent(s): 9b38b2b

Upload 7 files

Browse files
app.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import user, rm_predict
2
+ import gradio as gr
3
+
4
+ app1 = user.demo
5
+ app2 = rm_predict.demo
6
+
7
+ gr.Tabs([app1, app2]).launch()
gradient_boosting_regressor_model.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f94670712fa53f6fa0b031b8bac9e8e60a841a7fcb1783d7dd5fff1d633a6c4
3
+ size 179724
predictions.csv ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Identifier,Tire Weight,Predicted Material CO2 Emissions,Raw Material Transportation CO2 Emissions,Fuel CO2 Emissions,Plant Energy Consumption CO2 Emissions
2
+ tire1,8.6,18.916768372987377,0.4815999999999999,140.5,900.0
3
+ tire2,9.5,21.025089181790005,5.319999999999999,421.5,2250.0
4
+ tire3,10.5,17.557486755006813,8.82,72.25,16.2
5
+ tire4,10.5,17.557486755006813,8.82,37.57,16.2
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio==3.0
2
+ matplotlib==3.5.2
3
+ Pillow==9.2.0
4
+ scikit-learn==1.0.2
5
+ numpy==1.22.4
6
+ joblib==1.1.0
7
+ csv==1.0.0
rm_predict.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import joblib
3
+ import numpy as np
4
+ import csv
5
+
6
+ # Load your trained Gradient Boosted Trees model
7
+ model = joblib.load('models/gradient_boosting_regressor_model.joblib')
8
+
9
+ # Define emission factors directly
10
+ emission_factors = {
11
+ 'Synthetic Rubber': 2.4,
12
+ 'Natural Rubber': 0.639,
13
+ 'Carbon Black': 3.2,
14
+ 'Steel Cord': 2.46,
15
+ 'Silica': 2.06,
16
+ 'Process Oil': 1.61,
17
+ 'Bead Wire': 2.46,
18
+ 'Zinc Oxide': 2.01,
19
+ 'Sulfur': 0.008
20
+ }
21
+
22
+ # Fuel emission coefficients (kgCO2e per unit)
23
+ fuel_emission_factors = {
24
+ 'Benzene': 2.81,
25
+ 'Kerosene': 2.76,
26
+ 'Diesel fuel': 2.89,
27
+ 'A heavy oil': 3.08,
28
+ 'B • C heavy oil': 3.34,
29
+ 'Liquefied petroleum gas (LPG)': 3.78,
30
+ 'Liquefied natural gas (LNG)': 4.23,
31
+ 'Fuel coal': 2.37
32
+ }
33
+
34
+ def get_next_identifier():
35
+ file_path = 'predictions.csv'
36
+ try:
37
+ with open(file_path, 'r') as file:
38
+ last_line = None
39
+ for last_line in csv.reader(file): pass
40
+ if last_line and last_line[0].startswith('tire'):
41
+ last_num = int(last_line[0][4:])
42
+ return f"tire{last_num + 1}"
43
+ except FileNotFoundError:
44
+ pass
45
+ return "tire1"
46
+
47
+ def save_prediction_results(identifier, tire_weight, predicted_emission, transport_emission, fuel_emission, plant_emission):
48
+ file_path = 'predictions.csv'
49
+ # Attempt to write the header only if the file is being created (i.e., doesn't exist)
50
+ try:
51
+ with open(file_path, 'x', newline='') as file:
52
+ writer = csv.writer(file)
53
+ writer.writerow(['Identifier', 'Tire Weight', 'Predicted Material CO2 Emissions', 'Raw Material Transportation CO2 Emissions', 'Fuel CO2 Emissions', 'Plant Energy Consumption CO2 Emissions'])
54
+ except FileExistsError:
55
+ pass # File already exists, proceed to append data without writing the header
56
+
57
+ with open(file_path, 'a', newline='') as file:
58
+ writer = csv.writer(file)
59
+ writer.writerow([identifier, tire_weight, predicted_emission, transport_emission, fuel_emission, plant_emission])
60
+
61
+ def predict_and_calculate_emissions(average_distance, fuel_type, fuel_quantity, energy_consumption, tire_weight, synthetic_rubber_weight, natural_rubber_weight, carbon_black_weight, steel_cord_weight, silica_weight, process_oil_weight, bead_wire_weight, zinc_oxide_weight, sulfur_weight):
62
+ weights = np.array([synthetic_rubber_weight, natural_rubber_weight, carbon_black_weight, steel_cord_weight, silica_weight, process_oil_weight, bead_wire_weight, zinc_oxide_weight, sulfur_weight])
63
+ emissions = weights * np.array([emission_factors[mat] for mat in emission_factors])
64
+ features = np.concatenate(([tire_weight], weights, emissions)).reshape(1, -1)
65
+ predicted_emission = model.predict(features)[0]
66
+
67
+ # Additional Calculations
68
+ transport_emission = tire_weight * 0.00056 * average_distance
69
+ fuel_emission = fuel_quantity * fuel_emission_factors[fuel_type]
70
+ plant_emission = energy_consumption * 0.9
71
+
72
+ # Save results
73
+ identifier = get_next_identifier()
74
+ save_prediction_results(identifier, tire_weight, predicted_emission, transport_emission, fuel_emission, plant_emission)
75
+
76
+ return predicted_emission, transport_emission, fuel_emission, plant_emission
77
+
78
+ # Assuming the predict_and_calculate_emissions function is defined correctly as per your previous code snippet
79
+
80
+ with gr.Blocks() as demo:
81
+ gr.Markdown("### Predict Total CO2 Emissions")
82
+ gr.Markdown("Enter the details to predict emissions and calculate additional environmental impacts.")
83
+
84
+ # Tire and raw material weights
85
+ with gr.Row():
86
+ tire_weight = gr.Number(label="Tire Weight (kg)")
87
+ with gr.Row():
88
+ synthetic_rubber_weight = gr.Number(label="Synthetic Rubber Weight (kg)", value=0)
89
+ natural_rubber_weight = gr.Number(label="Natural Rubber Weight (kg)", value=0)
90
+ carbon_black_weight = gr.Number(label="Carbon Black Weight (kg)", value=0)
91
+ with gr.Row():
92
+ steel_cord_weight = gr.Number(label="Steel Cord Weight (kg)", value=0)
93
+ silica_weight = gr.Number(label="Silica Weight (kg)", value=0)
94
+ process_oil_weight = gr.Number(label="Process Oil Weight (kg)", value=0)
95
+ with gr.Row():
96
+ bead_wire_weight = gr.Number(label="Bead Wire Weight (kg)", value=0)
97
+ zinc_oxide_weight = gr.Number(label="Zinc Oxide Weight (kg)", value=0)
98
+ sulfur_weight = gr.Number(label="Sulfur Weight (kg)", value=0)
99
+
100
+ # Fuel type selection in its own row
101
+ with gr.Row():
102
+ fuel_type = gr.Radio(['Benzene', 'Kerosene', 'Diesel fuel', 'A heavy oil', 'B • C heavy oil', 'Liquefied petroleum gas (LPG)', 'Liquefied natural gas (LNG)', 'Fuel coal'], label="Fuel Type")
103
+
104
+ # Additional parameters in a compact 3-box layout
105
+ with gr.Row():
106
+ average_distance = gr.Number(label="Average Transportation Distance (km)", value=0)
107
+ fuel_quantity = gr.Number(label="Fuel Quantity (liters/kg)", value=0)
108
+ energy_consumption = gr.Number(label="Plant Energy Consumption (kWh per tire)", value=0)
109
+
110
+ btn_predict = gr.Button("Predict", align="right")
111
+
112
+ # Outputs
113
+ predicted_material_emission = gr.Textbox(label="Predicted Material CO2 Emissions (kgCO2e)")
114
+ raw_material_transportation_emission = gr.Textbox(label="Transportation CO2 Emissions (kgCO2e)")
115
+ fuel_emission = gr.Textbox(label="Fuel CO2 Emissions (kgCO2e)")
116
+ plant_energy_consumption_emission = gr.Textbox(label="Plant Energy CO2 Emissions (kgCO2e)")
117
+
118
+ # Button to execute the function
119
+
120
+
121
+ btn_predict.click(
122
+ fn=predict_and_calculate_emissions,
123
+ inputs=[
124
+ average_distance, fuel_type, fuel_quantity, energy_consumption,
125
+ tire_weight, synthetic_rubber_weight, natural_rubber_weight, carbon_black_weight,
126
+ steel_cord_weight, silica_weight, process_oil_weight, bead_wire_weight,
127
+ zinc_oxide_weight, sulfur_weight
128
+ ],
129
+ outputs=[
130
+ predicted_material_emission, raw_material_transportation_emission,
131
+ fuel_emission, plant_energy_consumption_emission
132
+ ]
133
+ )
134
+
135
+ demo.launch()
user.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import csv
3
+ import matplotlib.pyplot as plt
4
+ import io
5
+ from PIL import Image
6
+
7
+ def display_emissions_data_and_chart(tire_id):
8
+ file_path = 'predictions.csv'
9
+ try:
10
+ with open(file_path, mode='r', newline='') as file:
11
+ reader = csv.DictReader(file)
12
+ for row in reader:
13
+ if row['Identifier'] == tire_id:
14
+ # Extracting data for pie chart
15
+ emissions_labels = [
16
+ 'Predicted Material CO2',
17
+ 'Raw Material Transportation CO2',
18
+ 'Fuel CO2',
19
+ 'Plant Energy Consumption CO2'
20
+ ]
21
+ emissions_values = [
22
+ float(row.get('Predicted Material CO2 Emissions', 0)),
23
+ float(row.get('Raw Material Transportation CO2 Emissions', 0)),
24
+ float(row.get('Fuel CO2 Emissions', 0)),
25
+ float(row.get('Plant Energy Consumption CO2 Emissions', 0))
26
+ ]
27
+
28
+ # Generate Pie Chart
29
+ fig, ax = plt.subplots(figsize=(9, 6)) # Adjusted figure size to be 50% larger
30
+ ax.pie(emissions_values, labels=emissions_labels, autopct='%1.1f%%', startangle=90)
31
+ ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
32
+
33
+ buf = io.BytesIO()
34
+ plt.savefig(buf, format='png', bbox_inches='tight')
35
+ buf.seek(0)
36
+ plt.close(fig)
37
+
38
+ # Convert bytes to PIL Image
39
+ buf_image = Image.open(buf)
40
+ return buf_image
41
+
42
+ except FileNotFoundError:
43
+ return "The predictions.csv file was not found."
44
+
45
+ # Define a wrapper function for Gradio that calls the display function
46
+ def get_emissions_data(tire_id):
47
+ image = display_emissions_data_and_chart(tire_id)
48
+ if isinstance(image, Image.Image):
49
+ return image
50
+ else:
51
+ # If the result isn't an image, return a placeholder or error image
52
+ return Image.new('RGB', (200, 200), color='red')
53
+
54
+ # Set up the Gradio Blocks
55
+ with gr.Blocks() as demo:
56
+ with gr.Row():
57
+ tire_id_input = gr.Textbox(label="Enter Tire ID")
58
+ submit_button = gr.Button("Submit")
59
+
60
+ output_image = gr.Image(label="Emissions Data Chart")
61
+
62
+ submit_button.click(
63
+ fn=get_emissions_data,
64
+ inputs=tire_id_input,
65
+ outputs=output_image
66
+ )
67
+
68
+ demo.launch()
utils.py ADDED
File without changes