Spaces:
Sleeping
Sleeping
Create app_not_clean.py
Browse files- app_not_clean.py +172 -0
app_not_clean.py
ADDED
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
12 |
+
# Unique phase elements
|
13 |
+
|
14 |
+
# Load access tokens
|
15 |
+
WRITE_TOKEN = os.environ.get("WRITE_PER") # write
|
16 |
+
|
17 |
+
# Logs repo path
|
18 |
+
dataset_url = "https://huggingface.co/datasets/sandl/upload_alloy_hardness"
|
19 |
+
dataset_path = "logs_alloy_hardness.csv"
|
20 |
+
|
21 |
+
scaling_factors = {'PROPERTY: Calculated Density (g/cm$^3$)': (2.7, 13.7),
|
22 |
+
'PROPERTY: Calculated Young modulus (GPa)': (66, 336),
|
23 |
+
'PROPERTY: HV': (94.7, 1183.0)}
|
24 |
+
|
25 |
+
input_mapping = {'PROPERTY: BCC/FCC/other': {'BCC': 0, 'FCC': 1, 'OTHER': 2},# 'nan': 2},
|
26 |
+
'PROPERTY: Processing method': {'ANNEAL': 0, 'CAST': 1, 'OTHER': 2, 'POWDER': 3, 'WROUGHT': 4},# 'nan': 2},
|
27 |
+
'PROPERTY: Microstructure': {'B2': 0, 'B2+BCC': 1, 'B2+Sec.': 2, 'BCC': 3, 'BCC+B2': 4, 'BCC+B2+Laves': 5,
|
28 |
+
'BCC+B2+Sec.': 6, 'BCC+BCC': 7, 'BCC+BCC+HCP': 8, 'BCC+BCC+Laves(C15)': 9,
|
29 |
+
'BCC+FCC': 10, 'BCC+HCP': 11, 'BCC+Laves': 12, 'BCC+Laves(C14)': 13,
|
30 |
+
'BCC+Laves(C15)': 14, 'BCC+Laves+Sec.': 15, 'BCC+Sec.': 16, 'FCC': 17,
|
31 |
+
'FCC+B2': 18, 'FCC+B2+Sec.': 19, 'FCC+BCC': 20, 'FCC+BCC+B2': 21, 'FCC+BCC+B2+Sec.': 22,
|
32 |
+
'FCC+BCC+Sec.': 23, 'FCC+FCC': 24, 'FCC+HCP': 25, 'FCC+L12': 26, 'FCC+L12+Sec.': 27,
|
33 |
+
'FCC+Sec.': 28, 'OTHER': 29}, #'nan': 29},
|
34 |
+
'PROPERTY: Single/Multiphase': {'M': 0, 'S': 1, 'OTHER': 3}} #'nan': 3,
|
35 |
+
|
36 |
+
unique_phase_elements = ['B2', 'BCC', 'FCC', 'HCP', 'L12', 'Laves', 'Laves(C14)', 'Laves(C15)', 'Sec.', 'OTHER']
|
37 |
+
|
38 |
+
input_cols = {
|
39 |
+
"PROPERTY: Alloy formula": "(PROPERTY: Alloy formula) "
|
40 |
+
"Enter alloy formula using proportions representation (i.e. Al0.25 Co1 Fe1 Ni1)",
|
41 |
+
"PROPERTY: Single/Multiphase": "(PROPERTY: Single/Multiphase) "
|
42 |
+
"Choose between Single (S), Multiphase (M) and other (OTHER)",
|
43 |
+
"PROPERTY: BCC/FCC/other": "(PROPERTY: BCC/FCC/other) "
|
44 |
+
"Choose between BCC, FCC and other ",
|
45 |
+
"PROPERTY: Processing method": "(PROPERTY: Processing method) "
|
46 |
+
"Choose your processing method (ANNEAL, CAST, POWDER, WROUGHT or OTHER)",
|
47 |
+
"PROPERTY: Microstructure": "(PROPERTY: Microstructure) "
|
48 |
+
"Choose the microstructure (SEC means the secondary/tertiary microstructure is not one of FCC, BCC, HCP, L12, B2, Laves, Laves (C14), Laves (C15))",
|
49 |
+
}
|
50 |
+
|
51 |
+
def process_microstructure(list_phases):
|
52 |
+
permutations = list(itertools.permutations(list_phases))
|
53 |
+
permutations_strings = [str('+'.join(list(e))) for e in permutations]
|
54 |
+
for e in permutations_strings:
|
55 |
+
if e in list(input_mapping['PROPERTY: Microstructure'].keys()):
|
56 |
+
return e
|
57 |
+
return 'OTHER'
|
58 |
+
|
59 |
+
def write_logs(message, message_type="Prediction"):
|
60 |
+
"""
|
61 |
+
Write logs
|
62 |
+
"""
|
63 |
+
with Repository(local_dir="data", clone_from=dataset_url, use_auth_token=WRITE_TOKEN).commit(commit_message="from private", blocking=False):
|
64 |
+
with open(dataset_path, "a") as csvfile:
|
65 |
+
writer = csv.DictWriter(csvfile, fieldnames=["name", "message", "time"])
|
66 |
+
writer.writerow(
|
67 |
+
{"name": message_type, "message": message, "time": str(datetime.now())}
|
68 |
+
)
|
69 |
+
return
|
70 |
+
|
71 |
+
def predict(x, request: gr.Request):
|
72 |
+
"""
|
73 |
+
Predict the hardness using the ML model. Input data is a dataframe
|
74 |
+
"""
|
75 |
+
loaded_model = tf.keras.models.load_model("hardness.h5")
|
76 |
+
x = x.replace("", 0)
|
77 |
+
x = np.asarray(x).astype("float32")
|
78 |
+
y = loaded_model.predict(x)[0][0]
|
79 |
+
minimum, maximum = scaling_factors['PROPERTY: HV']
|
80 |
+
print("Prediction is ", y)
|
81 |
+
if request is not None: # Verify if request is not None (when building the app the first request is None)
|
82 |
+
message = f"{request.username}_{request.client.host}"
|
83 |
+
print("MESSAGE")
|
84 |
+
print(message)
|
85 |
+
res = write_logs(message)
|
86 |
+
interpret_fig = utils.interpret(x)
|
87 |
+
return round(y*(maximum-minimum)+minimum, 2), 12, interpret_fig
|
88 |
+
|
89 |
+
|
90 |
+
def predict_from_tuple(in1, in2, in3, in4, in5, request: gr.Request):
|
91 |
+
"""
|
92 |
+
Predict the hardness using the ML model. Input data is a tuple. Input order should be the same as the cols list
|
93 |
+
"""
|
94 |
+
input_tuple = (in1, in2, in3, in4, in5)
|
95 |
+
formula = utils.normalize_and_alphabetize_formula(in1)
|
96 |
+
density = utils.calculate_density(formula)
|
97 |
+
young_modulus = utils.calculate_youngs_modulus(formula)
|
98 |
+
input_dict = {}
|
99 |
+
|
100 |
+
in2 = input_mapping['PROPERTY: Single/Multiphase'][str(in2)]
|
101 |
+
input_dict['PROPERTY: Single/Multiphase'] = [int(in2)]
|
102 |
+
|
103 |
+
in3 = input_mapping['PROPERTY: BCC/FCC/other'][str(in3)]
|
104 |
+
input_dict['PROPERTY: BCC/FCC/other'] = [int(in3)]
|
105 |
+
|
106 |
+
in4 = input_mapping['PROPERTY: Processing method'][str(in4)]
|
107 |
+
input_dict['PROPERTY: Processing method'] = [int(in4)]
|
108 |
+
|
109 |
+
in5 = process_microstructure(in5)
|
110 |
+
in5 = input_mapping['PROPERTY: Microstructure'][in5]
|
111 |
+
input_dict['PROPERTY: Microstructure'] = [int(in5)]
|
112 |
+
|
113 |
+
density_scaling_factors = scaling_factors['PROPERTY: Calculated Density (g/cm$^3$)']
|
114 |
+
density = (density-density_scaling_factors[0])/(
|
115 |
+
density_scaling_factors[1]-density_scaling_factors[0])
|
116 |
+
input_dict['PROPERTY: Calculated Density (g/cm$^3$)'] = [float(density)]
|
117 |
+
|
118 |
+
|
119 |
+
ym_scaling_factors = scaling_factors['PROPERTY: Calculated Young modulus (GPa)']
|
120 |
+
young_modulus = (young_modulus-ym_scaling_factors[0])/(
|
121 |
+
ym_scaling_factors[1]-ym_scaling_factors[0])
|
122 |
+
input_dict['PROPERTY: Calculated Young modulus (GPa)'] = [float(young_modulus)]
|
123 |
+
|
124 |
+
input_df = pd.DataFrame.from_dict(input_dict)
|
125 |
+
one_hot = utils.turn_into_one_hot(input_df, input_mapping)
|
126 |
+
print(one_hot.columns)
|
127 |
+
return predict(one_hot, request)
|
128 |
+
|
129 |
+
|
130 |
+
input_formula = gr.Textbox(
|
131 |
+
lines=1, placeholder=input_cols["PROPERTY: Alloy formula"], label=input_cols["PROPERTY: Alloy formula"]
|
132 |
+
)
|
133 |
+
input_phase = gr.Dropdown(
|
134 |
+
choices=list(input_mapping["PROPERTY: Single/Multiphase"].keys()),
|
135 |
+
label=input_cols["PROPERTY: Single/Multiphase"],
|
136 |
+
)
|
137 |
+
input_bccfcc = gr.Dropdown(
|
138 |
+
choices=list(input_mapping["PROPERTY: BCC/FCC/other"].keys()),
|
139 |
+
label=input_cols["PROPERTY: BCC/FCC/other"],
|
140 |
+
)
|
141 |
+
input_processing = gr.Dropdown(
|
142 |
+
choices=list(input_mapping["PROPERTY: Processing method"].keys()),
|
143 |
+
label=input_cols["PROPERTY: Processing method"],
|
144 |
+
)
|
145 |
+
input_microstructure = gr.CheckboxGroup(
|
146 |
+
choices=unique_phase_elements, #list(input_mapping["PROPERTY: Microstructure"].keys()),
|
147 |
+
label=input_cols["PROPERTY: Microstructure"],
|
148 |
+
)
|
149 |
+
input_list = [input_formula, input_phase, input_bccfcc, input_processing, input_microstructure]
|
150 |
+
|
151 |
+
|
152 |
+
examples_inputs = ['Al0.25 Co1 Fe1 Ni1', 'S', 'BCC', 'CAST', ['B2', 'BCC']]
|
153 |
+
|
154 |
+
# Version where input is a DataFrame
|
155 |
+
# demo = gr.Interface(fn=predict,
|
156 |
+
# inputs=gr.DataFrame(headers=cols),
|
157 |
+
# outputs=gr.Text(label="Hardness (in HV)"))
|
158 |
+
|
159 |
+
|
160 |
+
demo = gr.Interface(
|
161 |
+
fn=predict_from_tuple,
|
162 |
+
inputs=input_list,
|
163 |
+
outputs=[gr.Text(label="Hardness (in HV)"), gr.Text(label="Uncertainty (%)"), gr.Plot(label="Interpretation")],
|
164 |
+
title="Predict your alloy's hardness",
|
165 |
+
description="This AI model provides the estimation of hardness based on the input alloy description",
|
166 |
+
examples=[examples_inputs],
|
167 |
+
)
|
168 |
+
|
169 |
+
|
170 |
+
|
171 |
+
if __name__ == "__main__":
|
172 |
+
demo.launch(show_error=True)
|