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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import csv
|
3 |
+
import gradio as gr
|
4 |
+
import tensorflow as tf
|
5 |
+
import numpy as np
|
6 |
+
import pandas as pd
|
7 |
+
from datetime import datetime
|
8 |
+
import utils
|
9 |
+
from huggingface_hub import Repository
|
10 |
+
import itertools
|
11 |
+
import time
|
12 |
+
import cv2
|
13 |
+
|
14 |
+
# Unique phase elements
|
15 |
+
|
16 |
+
# Load access tokens
|
17 |
+
WRITE_TOKEN = os.environ.get("WRITE_PER") # write
|
18 |
+
|
19 |
+
# Logs repo path
|
20 |
+
dataset_url = "https://huggingface.co/datasets/sandl/upload_alloy_hardness"
|
21 |
+
dataset_path = "logs_alloy_hardness.csv"
|
22 |
+
|
23 |
+
scaling_factors = {'PROPERTY: Calculated Density (g/cm$^3$)': (5.5, 13.7),
|
24 |
+
'PROPERTY: Calculated Young modulus (GPa)': (77.0, 336.0),
|
25 |
+
'PROPERTY: HV': (107.0, 1183.0),
|
26 |
+
'PROPERTY: YS (MPa)': (62.0, 3416.0)}
|
27 |
+
|
28 |
+
input_mapping = {'PROPERTY: BCC/FCC/other': {'BCC': 0, 'FCC': 1, 'OTHER': 2},#, 'nan': 2},
|
29 |
+
'PROPERTY: Processing method': {'ANNEAL': 0, 'CAST': 1, 'OTHER': 2, 'POWDER': 3, 'WROUGHT': 4},#, 'nan': 2},
|
30 |
+
'PROPERTY: Microstructure': {'B2': 0, 'B2+BCC': 1, 'B2+L12': 2, 'B2+Laves+Sec.': 3, 'B2+Sec.': 4, 'BCC': 5,
|
31 |
+
'BCC+B2': 6, 'BCC+B2+FCC': 7, 'BCC+B2+FCC+Sec.': 8, 'BCC+B2+L12': 9, 'BCC+B2+Laves': 10,
|
32 |
+
'BCC+B2+Sec.': 11, 'BCC+BCC': 12, 'BCC+BCC+HCP': 13, 'BCC+BCC+Laves': 14,
|
33 |
+
'BCC+BCC+Laves(C14)': 15, 'BCC+BCC+Laves(C15)': 16, 'BCC+FCC': 17, 'BCC+HCP': 18,
|
34 |
+
'BCC+Laves': 19, 'BCC+Laves(C14)': 20, 'BCC+Laves(C15)': 21, 'BCC+Laves+Sec.': 22,
|
35 |
+
'BCC+Sec.': 23, 'FCC': 24, 'FCC+B2': 25, 'FCC+B2+Sec.': 26, 'FCC+BCC': 27,
|
36 |
+
'FCC+BCC+B2': 28, 'FCC+BCC+B2+Sec.': 29, 'FCC+BCC+BCC': 30, 'FCC+BCC+Sec.': 31,
|
37 |
+
'FCC+FCC': 32, 'FCC+HCP': 33, 'FCC+HCP+Sec.': 34, 'FCC+L12': 35, 'FCC+L12+B2': 36,
|
38 |
+
'FCC+L12+Sec.': 37, 'FCC+Laves': 38, 'FCC+Laves(C14)': 39, 'FCC+Laves+Sec.': 40,
|
39 |
+
'FCC+Sec.': 41, 'L12+B2': 42, 'Laves(C14)+Sec.': 43, 'OTHER': 44},#, 'nan': 44},
|
40 |
+
'PROPERTY: Single/Multiphase': {'': 0, 'M': 1, 'S': 2, 'OTHER': 3}}#, 'nan': 3}}
|
41 |
+
|
42 |
+
unique_phase_elements = ['B2', 'BCC', 'FCC', 'HCP', 'L12', 'Laves', 'Laves(C14)', 'Laves(C15)', 'Sec.', 'OTHER']
|
43 |
+
|
44 |
+
input_cols = {
|
45 |
+
"PROPERTY: Alloy formula": "(PROPERTY: Alloy formula) "
|
46 |
+
"Enter alloy formula using proportions representation (i.e. Al0.25 Co1 Fe1 Ni1)",
|
47 |
+
"PROPERTY: Single/Multiphase": "(PROPERTY: Single/Multiphase) "
|
48 |
+
"Choose between Single (S), Multiphase (M) and other (OTHER)",
|
49 |
+
"PROPERTY: BCC/FCC/other": "(PROPERTY: BCC/FCC/other) "
|
50 |
+
"Choose between BCC, FCC and other ",
|
51 |
+
"PROPERTY: Processing method": "(PROPERTY: Processing method) "
|
52 |
+
"Choose your processing method (ANNEAL, CAST, POWDER, WROUGHT or OTHER)",
|
53 |
+
"PROPERTY: Microstructure": "(PROPERTY: Microstructure) "
|
54 |
+
"Choose the microstructure (SEC means the secondary/tertiary microstructure is not one of FCC, BCC, HCP, L12, B2, Laves, Laves (C14), Laves (C15))",
|
55 |
+
}
|
56 |
+
|
57 |
+
def process_microstructure(list_phases):
|
58 |
+
permutations = list(itertools.permutations(list_phases))
|
59 |
+
permutations_strings = [str('+'.join(list(e))) for e in permutations]
|
60 |
+
for e in permutations_strings:
|
61 |
+
if e in list(input_mapping['PROPERTY: Microstructure'].keys()):
|
62 |
+
return e
|
63 |
+
return 'OTHER'
|
64 |
+
|
65 |
+
def write_logs(message, message_type="Prediction"):
|
66 |
+
"""
|
67 |
+
Write logs
|
68 |
+
"""
|
69 |
+
with Repository(local_dir="data", clone_from=dataset_url, use_auth_token=WRITE_TOKEN).commit(commit_message="from private", blocking=False):
|
70 |
+
with open(dataset_path, "a") as csvfile:
|
71 |
+
writer = csv.DictWriter(csvfile, fieldnames=["name", "message", "time"])
|
72 |
+
writer.writerow(
|
73 |
+
{"name": message_type, "message": message, "time": str(datetime.now())}
|
74 |
+
)
|
75 |
+
return
|
76 |
+
|
77 |
+
def predict(x, request: gr.Request):
|
78 |
+
"""
|
79 |
+
Predict the hardness and yield strength using the ML model. Input data is a dataframe
|
80 |
+
"""
|
81 |
+
loaded_model = tf.keras.models.load_model("hardness.h5")
|
82 |
+
print("summary is", loaded_model.summary())
|
83 |
+
x = x.replace("", 0)
|
84 |
+
x = np.asarray(x).astype("float32")
|
85 |
+
y = loaded_model.predict(x)
|
86 |
+
y_hardness = y[0][0]
|
87 |
+
y_ys = y[0][1]
|
88 |
+
minimum_hardness, maximum_hardness = scaling_factors['PROPERTY: HV']
|
89 |
+
minimum_ys, maximum_ys = scaling_factors['PROPERTY: YS (MPa)']
|
90 |
+
print("Prediction is ", y)
|
91 |
+
if request is not None: # Verify if request is not None (when building the app the first request is None)
|
92 |
+
message = f"{request.username}_{request.client.host}"
|
93 |
+
print("MESSAGE")
|
94 |
+
print(message)
|
95 |
+
res = write_logs(message)
|
96 |
+
interpret_fig = utils.interpret(x)
|
97 |
+
return (round(y_hardness*(maximum_hardness-minimum_hardness)+minimum_hardness, 2), 12,
|
98 |
+
round(y_ys*(maximum_ys-minimum_ys)+minimum_ys, 2), 4.8, interpret_fig)
|
99 |
+
|
100 |
+
|
101 |
+
def predict_from_tuple(in1, in2, in3, in4, in5, request: gr.Request):
|
102 |
+
"""
|
103 |
+
Predict the hardness using the ML model. Input data is a tuple. Input order should be the same as the cols list
|
104 |
+
"""
|
105 |
+
input_tuple = (in1, in2, in3, in4, in5)
|
106 |
+
formula = utils.normalize_and_alphabetize_formula(in1)
|
107 |
+
density = utils.calculate_density(formula)
|
108 |
+
young_modulus = utils.calculate_youngs_modulus(formula)
|
109 |
+
input_dict = {}
|
110 |
+
|
111 |
+
in2 = input_mapping['PROPERTY: Single/Multiphase'][str(in2)]
|
112 |
+
input_dict['PROPERTY: Single/Multiphase'] = [int(in2)]
|
113 |
+
|
114 |
+
in3 = input_mapping['PROPERTY: BCC/FCC/other'][str(in3)]
|
115 |
+
input_dict['PROPERTY: BCC/FCC/other'] = [int(in3)]
|
116 |
+
|
117 |
+
in4 = input_mapping['PROPERTY: Processing method'][str(in4)]
|
118 |
+
input_dict['PROPERTY: Processing method'] = [int(in4)]
|
119 |
+
|
120 |
+
in5 = process_microstructure(in5)
|
121 |
+
in5 = input_mapping['PROPERTY: Microstructure'][in5]
|
122 |
+
input_dict['PROPERTY: Microstructure'] = [int(in5)]
|
123 |
+
|
124 |
+
density_scaling_factors = scaling_factors['PROPERTY: Calculated Density (g/cm$^3$)']
|
125 |
+
density = (density-density_scaling_factors[0])/(
|
126 |
+
density_scaling_factors[1]-density_scaling_factors[0])
|
127 |
+
input_dict['PROPERTY: Calculated Density (g/cm$^3$)'] = [float(density)]
|
128 |
+
|
129 |
+
|
130 |
+
ym_scaling_factors = scaling_factors['PROPERTY: Calculated Young modulus (GPa)']
|
131 |
+
young_modulus = (young_modulus-ym_scaling_factors[0])/(
|
132 |
+
ym_scaling_factors[1]-ym_scaling_factors[0])
|
133 |
+
input_dict['PROPERTY: Calculated Young modulus (GPa)'] = [float(young_modulus)]
|
134 |
+
|
135 |
+
input_df = pd.DataFrame.from_dict(input_dict)
|
136 |
+
one_hot = utils.turn_into_one_hot(input_df, input_mapping)
|
137 |
+
print("One hot columns are ", one_hot.columns)
|
138 |
+
return predict(one_hot, request)
|
139 |
+
|
140 |
+
|
141 |
+
def upload_csv(x):
|
142 |
+
print(x)
|
143 |
+
print(x.name)
|
144 |
+
df = pd.read_csv(x.name, sep=",")
|
145 |
+
print("Input dataframe")
|
146 |
+
print(df.shape)
|
147 |
+
cols = list(df.columns)
|
148 |
+
return df, gr.update(choices=cols)
|
149 |
+
|
150 |
+
|
151 |
+
def train_model(x, target_cols):
|
152 |
+
print("Selected target columns")
|
153 |
+
print(target_cols)
|
154 |
+
time.sleep(6)
|
155 |
+
performance_plot = cv2.imread("model_performance.png")
|
156 |
+
metrics = pd.DataFrame([[0.09, 0.017]], columns=["RMSE", "Loss"])
|
157 |
+
return "Model successfully adapted to your data!", performance_plot, metrics
|
158 |
+
|
159 |
+
|
160 |
+
|
161 |
+
|
162 |
+
example_inputs = ['Al0.25 Co1 Fe1 Ni1', 'S', 'BCC', 'CAST', ['B2', 'Sec.']]
|
163 |
+
|
164 |
+
css_styling = """#submit {background: #1eccd8}
|
165 |
+
#submit:hover {background: #a2f1f6}
|
166 |
+
.output-image, .input-image, .image-preview {height: 250px !important}
|
167 |
+
.output-plot {height: 250px !important}"""
|
168 |
+
|
169 |
+
light_theme_colors = gr.themes.Color(c50="#e4f3fa", # Dataframe background cell content - light mode only
|
170 |
+
c100="#e4f3fa", # Top corner of clear button in light mode + markdown text in dark mode
|
171 |
+
c200="#a1c6db", # Component borders
|
172 |
+
c300="#FFFFFF", #
|
173 |
+
c400="#e4f3fa", # Footer text
|
174 |
+
c500="#0c1538", # Text of component headers in light mode only
|
175 |
+
c600="#a1c6db", # Top corner of button in dark mode
|
176 |
+
c700="#475383", # Button text in light mode + component borders in dark mode
|
177 |
+
c800="#0c1538", # Markdown text in light mode
|
178 |
+
c900="#a1c6db", # Background of dataframe - dark mode
|
179 |
+
c950="#0c1538") # Background in dark mode only
|
180 |
+
# secondary color used for highlight box content when typing in light mode, and download option in dark mode
|
181 |
+
# primary color used for login button in dark mode
|
182 |
+
osium_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="cyan", neutral_hue=light_theme_colors)
|
183 |
+
page_title = "Alloys' hardness and yield strength prediction"
|
184 |
+
favicon_path = "osiumai_favicon.ico"
|
185 |
+
logo_path = "osiumai_logo.jpg"
|
186 |
+
html = f"""<html> <link rel="icon" type="image/x-icon" href="file={favicon_path}">
|
187 |
+
<img src='file={logo_path}' alt='Osium AI logo' width='200' height='100'> </html>"""
|
188 |
+
|
189 |
+
|
190 |
+
with gr.Blocks(css=css_styling, title=page_title, theme=osium_theme) as demo:
|
191 |
+
#gr.HTML(html)
|
192 |
+
gr.Markdown("# <p style='text-align: center;'>Predict your alloy's hardness and yield strength</p>")
|
193 |
+
gr.Markdown("This AI model provides the estimation of hardness and yield strength based on the input alloy description")
|
194 |
+
with gr.Tab(label="Model adaptation"):
|
195 |
+
with gr.Row():
|
196 |
+
with gr.Column():
|
197 |
+
gr.Markdown("### Your input files")
|
198 |
+
input_file = gr.File(label="Your input files", file_count="single", elem_id="input_files")
|
199 |
+
with gr.Row():
|
200 |
+
clear_train_button = gr.Button("Clear")
|
201 |
+
# upload_button = gr.Button("Upload", elem_id="submit")
|
202 |
+
train_button = gr.Button("Train model", elem_id="submit")
|
203 |
+
with gr.Row():
|
204 |
+
with gr.Column():
|
205 |
+
gr.Markdown("### Your input csv")
|
206 |
+
# input_image1 = gr.Image(elem_classes="input-csv")
|
207 |
+
input_csv = gr.DataFrame(elem_classes="input-csv")
|
208 |
+
with gr.Column():
|
209 |
+
gr.Markdown("### Choose your target properties")
|
210 |
+
target_columns = gr.CheckboxGroup(choices=[], interactive=True, label="Target alloy properties")
|
211 |
+
|
212 |
+
with gr.Column():
|
213 |
+
gr.Markdown("### Your model adaptation")
|
214 |
+
output_text = gr.Textbox(label="Training results")
|
215 |
+
output_plot = gr.Image(label="Training performance", elem_classes="output-image")
|
216 |
+
output_performance = gr.DataFrame(label="Model performance")
|
217 |
+
|
218 |
+
with gr.Tab(label="Run your model"):
|
219 |
+
with gr.Row():
|
220 |
+
clear_button = gr.Button("Clear")
|
221 |
+
prediction_button = gr.Button("Predict", elem_id="submit")
|
222 |
+
with gr.Row():
|
223 |
+
with gr.Column(scale=0.25, min_width=80):
|
224 |
+
gr.Markdown("### Your alloy's characteristics")
|
225 |
+
input_formula = gr.Textbox(
|
226 |
+
lines=2, placeholder=input_cols["PROPERTY: Alloy formula"], label=input_cols["PROPERTY: Alloy formula"]
|
227 |
+
)
|
228 |
+
input_phase = gr.Dropdown(
|
229 |
+
choices=list(input_mapping["PROPERTY: Single/Multiphase"].keys()),
|
230 |
+
label=input_cols["PROPERTY: Single/Multiphase"],
|
231 |
+
)
|
232 |
+
input_bccfcc = gr.Dropdown(
|
233 |
+
choices=list(input_mapping["PROPERTY: BCC/FCC/other"].keys()),
|
234 |
+
label=input_cols["PROPERTY: BCC/FCC/other"],
|
235 |
+
)
|
236 |
+
input_processing = gr.Dropdown(
|
237 |
+
choices=list(input_mapping["PROPERTY: Processing method"].keys()),
|
238 |
+
label=input_cols["PROPERTY: Processing method"],
|
239 |
+
)
|
240 |
+
input_microstructure = gr.CheckboxGroup(
|
241 |
+
choices=unique_phase_elements, #list(input_mapping["PROPERTY: Microstructure"].keys()),
|
242 |
+
label=input_cols["PROPERTY: Microstructure"],
|
243 |
+
)
|
244 |
+
with gr.Column():
|
245 |
+
with gr.Row():
|
246 |
+
with gr.Column():
|
247 |
+
gr.Markdown("### Your alloy's hardness (HV)")
|
248 |
+
output_hardness = gr.Text(label="Hardness (in HV)")
|
249 |
+
output_hardness_uncertainty = gr.Text(label="Hardness uncertainty (%)")
|
250 |
+
with gr.Column():
|
251 |
+
gr.Markdown("### Your alloy's yield strength (MPa)")
|
252 |
+
output_ys = gr.Text(label="Yield Strength (MPa)")
|
253 |
+
output_ys_uncertainty = gr.Text(label="Yield strength uncertainty (%)")
|
254 |
+
with gr.Row():
|
255 |
+
with gr.Column():
|
256 |
+
with gr.Row():
|
257 |
+
gr.Markdown("### Interpretation of hardness prediction")
|
258 |
+
gr.Markdown("### Interpretation of yield strength prediction")
|
259 |
+
with gr.Row():
|
260 |
+
output_interpretation = gr.Plot(label="Interpretation")
|
261 |
+
with gr.Row():
|
262 |
+
gr.Examples([example_inputs], [input_formula, input_phase, input_bccfcc, input_processing, input_microstructure])
|
263 |
+
|
264 |
+
train_button.click(
|
265 |
+
fn=train_model,
|
266 |
+
inputs=[input_csv, target_columns],
|
267 |
+
outputs=[output_text, output_plot, output_performance],
|
268 |
+
show_progress=True,
|
269 |
+
)
|
270 |
+
|
271 |
+
clear_train_button.click(
|
272 |
+
lambda x: [gr.update(value=None)] * 6,
|
273 |
+
[],
|
274 |
+
[input_file, input_csv, target_columns, output_text, output_plot, output_performance],
|
275 |
+
)
|
276 |
+
|
277 |
+
# upload_button.click(
|
278 |
+
# fn=upload_csv,
|
279 |
+
# inputs=[input_file],
|
280 |
+
# outputs=[input_csv, target_columns],
|
281 |
+
# show_progress=True,
|
282 |
+
# # every=2,
|
283 |
+
# )
|
284 |
+
input_file.change(
|
285 |
+
fn=upload_csv,
|
286 |
+
inputs=[input_file],
|
287 |
+
outputs=[input_csv, target_columns],
|
288 |
+
show_progress=True,
|
289 |
+
# every=2,
|
290 |
+
)
|
291 |
+
|
292 |
+
prediction_button.click(
|
293 |
+
fn=predict_from_tuple,
|
294 |
+
inputs=[input_formula, input_phase, input_bccfcc, input_processing, input_microstructure],
|
295 |
+
outputs=[
|
296 |
+
output_hardness,
|
297 |
+
output_hardness_uncertainty,
|
298 |
+
output_ys,
|
299 |
+
output_ys_uncertainty,
|
300 |
+
output_interpretation,
|
301 |
+
|
302 |
+
],
|
303 |
+
show_progress=True,
|
304 |
+
)
|
305 |
+
clear_button.click(
|
306 |
+
lambda x: [gr.update(value=None)] * 10,
|
307 |
+
[],
|
308 |
+
[
|
309 |
+
input_formula,
|
310 |
+
input_phase,
|
311 |
+
input_bccfcc,
|
312 |
+
input_processing,
|
313 |
+
input_microstructure,
|
314 |
+
output_hardness,
|
315 |
+
output_hardness_uncertainty,
|
316 |
+
output_ys,
|
317 |
+
output_ys_uncertainty,
|
318 |
+
output_interpretation,
|
319 |
+
],
|
320 |
+
)
|
321 |
+
|
322 |
+
|
323 |
+
if __name__ == "__main__":
|
324 |
+
demo.queue(concurrency_count=2)
|
325 |
+
demo.launch()
|