Spaces:
Sleeping
Sleeping
Update app.py
Browse files30 unmodified lines3132333435363735 unmodified lines7374757677787980818283848586878813 unmodified lines1021031041051061071081091101111121131141151161171181191201 unmodified line1221231241251261273 unmodified lines13113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617730 unmodified linesout, h = self.gru(x, h)return self.fc(out), h# Load all three Application Modelsstrength_model = xgb.XGBRegressor(); strength_model.load_model('models/yield_strength_final.json')degrad_model = xgb.XGBRegressor(); degrad_model.load_model('models/degradability_final.json')tg_model = xgb.XGBRegressor(); tg_model.load_model('models/tg_final.json')35 unmodified linesres = degrad_model.predict(feats.reshape(1, -1))[0]return f"Predicted Degradability Score: {res:.3f}"# --- 5. AUTONOMOUS DESIGN LOGIC ---def update_benchmarks(app_choice):if app_choice == "Structural / Aerospace":return "### 🧪 Targets: **Strength > 0.075 GPa** | SA < 5.0 | Degradability > 0.303"elif app_choice == "Battery Electrolytes":return "### 🧪 Targets: **Tg > 120°C** | SA < 5.0 | Strength > 0.05 GPa"else:return "### 🧪 Targets: **Degradability > 0.71** | SA < 5.0 | Strength > 0.03 GPa"def generate_and_screen(num_to_gen, app_mode):candidates = []for _ in range(num_to_gen):input_seq = torch.tensor([[char_to_int['<SOS>']]])13 unmodified linest = tg_model.predict(feats.reshape(1, -1))[0]sa = sascorer.calculateScore(mol) if sascorer else 5.0# Application-specific classificationif app_mode == "Structural / Aerospace":pass_p = s > 0.075elif app_mode == "Battery Electrolytes":pass_p = t > 120.0else:pass_p = d > 0.71status = "Excellent" if (pass_p and sa < 5.0) else "Review" if (pass_p or sa < 5.0) else "Bad"candidates.append({"p-SMILES": generated,"Yield Strength (GPa)": round(s, 4),"Tg (°C)": round(t, 2),"Degradability": round(d, 3),"SA Score": round(sa, 2),1 unmodified line})df = pd.DataFrame(candidates)output_path = tempfile.NamedTemporaryFile(delete=False, suffix=".csv").namedf.to_csv(output_path, index=False)return df, output_path3 unmodified linesgr.Markdown("<center><h1>🧪 PolymerDesignAI: Multi-Application Pipeline</h1></center>")with gr.Tab("Predict"):gr.Markdown("### Application-Specific Property Prediction")with gr.Row():with gr.Column():pred_mode = gr.Radio(["Structural (Strength)", "Battery (Tg)", "Biomedical (Degradability)"],value="Structural (Strength)",label="Select Property to Predict")smiles_in = gr.Textbox(label="Enter p-SMILES", placeholder="*CC*")pred_btn = gr.Button("Run Prediction", variant="primary")res_label = gr.Label(label="Prediction Result")with gr.Column():gr.Markdown("#### Interpretation Guide")gr.Markdown("""* **Strength**: > 0.08 GPa is High Performance.* **Tg**: Higher values indicate better thermal stability for batteries/aerospace.* **Degradability**: > 0.70 is highly degradable (Biomedical standard).""")pred_btn.click(predict_ui, [pred_mode, smiles_in], res_label)with gr.Tab("Autonomous Design"):gr.Markdown("### Integrated Generation + Screening")app_choice = gr.Dropdown(["Structural / Aerospace", "Battery Electrolytes", "Biomedical / Packaging"],value="Structural / Aerospace",label="Design Application Mode")# Dynamic Benchmark Displaybench_md = gr.Markdown("### 🧪 Targets: **Strength > 0.075 GPa** | SA < 5.0 | Degradability > 0.303")app_choice.change(update_benchmarks, app_choice, bench_md)with gr.Row():num = gr.Slider(1, 50, 10, step=1, label="Quantity to Generate")run = gr.Button("Run Design Pipeline", variant="primary")results_df = gr.DataFrame(label="AI-Generated Candidates")csv_out = gr.File(label="Download Full Results")run.click(generate_and_screen, [num, app_choice], [results_df, csv_out])demo.launch(auth=(os.environ.get("app_user"), os.environ.get("app_pass")),ssr_mode=False)30 unmodified lines3132333435363735 unmodified lines73747576777879808182838485868788899091929394959697989910010110210310410510610713 unmodified lines1211221231241251261271281291301311321331341351361371381391401 unmodified line1421431441451461471481491501511521531541551561571581591601611623 unmodified lines16616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421530 unmodified linesout, h = self.gru(x, h)return self.fc(out), h# Load Modelsstrength_model = xgb.XGBRegressor(); strength_model.load_model('models/yield_strength_final.json')degrad_model = xgb.XGBRegressor(); degrad_model.load_model('models/degradability_final.json')tg_model = xgb.XGBRegressor(); tg_model.load_model('models/tg_final.json')35 unmodified linesres = degrad_model.predict(feats.reshape(1, -1))[0]return f"Predicted Degradability Score: {res:.3f}"def batch_predict(app_choice, file_obj):try:df = pd.read_csv(file_obj.name)s_col = next((c for c in df.columns if 'smiles' in c.lower()), None)if not s_col: return None, "Error: CSV must have a 'SMILES' column."results = []for s in df[s_col]:feats = get_mff_features(str(s))if feats is not None:if app_choice == "Structural (Strength)":p = np.expm1(strength_model.predict(feats.reshape(1, -1)))[0]elif app_choice == "Battery (Tg)":p = tg_model.predict(feats.reshape(1, -1))[0]else:p = degrad_model.predict(feats.reshape(1, -1))[0]results.append(p)else:results.append(np.nan)df[f'Predicted_{app_choice}'] = resultsoutput_path = tempfile.NamedTemporaryFile(delete=False, suffix=".csv").namedf.to_csv(output_path, index=False)return df.head(10), output_pathexcept Exception as e:return None, f"Error processing file: {str(e)}"# --- 5. AUTONOMOUS DESIGN LOGIC ---def generate_and_screen(num_to_gen):candidates = []for _ in range(num_to_gen):input_seq = torch.tensor([[char_to_int['<SOS>']]])13 unmodified linest = tg_model.predict(feats.reshape(1, -1))[0]sa = sascorer.calculateScore(mol) if sascorer else 5.0# Universal Multi-Objective Classificationpass_strength = s > 0.075pass_tg = t > 120.0pass_deg = d > 0.303pass_sa = sa < 5.0num_passes = sum([pass_strength, pass_tg, pass_deg, pass_sa])if num_passes >= 3: status = "Excellent"elif num_passes == 2: status = "Review"else: status = "Bad"candidates.append({"p-SMILES": generated,"Strength (GPa)": round(s, 4),"Tg (°C)": round(t, 2),"Degradability": round(d, 3),"SA Score": round(sa, 2),1 unmodified line})df = pd.DataFrame(candidates)df = df.sort_values(by="Strength (GPa)", ascending=False)output_path = tempfile.NamedTemporaryFile(delete=False, suffix=".csv").namedf.to_csv(output_path, index=False)return df, output_pathdef calculate_universal_rank(df):if df is None or df.empty: return None, None# Normalize and Weight all targets equallys_norm = (df['Strength (GPa)'] - df['Strength (GPa)'].min()) / (df['Strength (GPa)'].max() - df['Strength (GPa)'].min() + 1e-6)t_norm = (df['Tg (°C)'] - df['Tg (°C)'].min()) / (df['Tg (°C)'].max() - df['Tg (°C)'].min() + 1e-6)d_norm = (df['Degradability'] - df['Degradability'].min()) / (df['Degradability'].max() - df['Degradability'].min() + 1e-6)sa_norm = 1 - ((df['SA Score'] - df['SA Score'].min()) / (df['SA Score'].max() - df['SA Score'].min() + 1e-6))df['Universal Rank Score'] = ((s_norm + t_norm + d_norm + sa_norm) / 4).round(4)df = df.sort_values(by="Universal Rank Score", ascending=False)output_path = tempfile.NamedTemporaryFile(delete=False, suffix=".csv").namedf.to_csv(output_path, index=False)return df, output_path3 unmodified linesgr.Markdown("<center><h1>🧪 PolymerDesignAI: Multi-Application Pipeline</h1></center>")with gr.Tab("Predict"):gr.Markdown("### Forward Property Prediction")with gr.Row():with gr.Column():pred_mode = gr.Radio(["Structural (Strength)", "Battery (Tg)", "Biomedical (Degradability)"],value="Structural (Strength)", label="Select Property")smiles_in = gr.Textbox(label="Enter p-SMILES manually", placeholder="*CC*")gr.Examples(examples=[["*CCCCCCNC(=O)NCCCCCCNC(=O)S*"], ["*Oc1ccc(C(C)(C)c2ccc(OC(=O)NCCCCCCNC(*)=O)cc2)cc1"], ["*[Se]c1ccc(C(=O)Nc2ccc(NC(=O)CCCCCCCC(=O)Nc3ccc(*)cc3)cc2)cc1"]],inputs=smiles_in, label="Quick Select Options")pred_btn = gr.Button("Predict Single", variant="primary")res_label = gr.Label(label="Prediction Result")with gr.Column():gr.Markdown("#### Batch Processing")file_in = gr.File(label="Upload CSV with 'SMILES' column")batch_btn = gr.Button("Run Batch Prediction")batch_df = gr.DataFrame(label="Preview (Top 10)")file_out = gr.File(label="Download Full Results")pred_btn.click(predict_ui, [pred_mode, smiles_in], res_label)batch_btn.click(batch_predict, [pred_mode, file_in], [batch_df, file_out])with gr.Tab("Autonomous Design"):gr.Markdown("### Integrated Generation + Screening")gr.Markdown("""**Application Targets:*** **Structural (Aerospace)**: Optimizing for High Yield Strength.* **Battery Electrolytes**: Optimizing for High Glass Transition Temperature (Tg).* **Biomedical**: Optimizing for High Degradability score.""")gr.Markdown("### 🧪 Universal Benchmarks: **Strength > 0.075 GPa** | **Tg > 120°C** | **Degradability > 0.303** | **SA < 5.0**")with gr.Row():num = gr.Slider(1, 50, 10, step=1, label="Quantity to Generate")run = gr.Button("Run Design Pipeline", variant="primary")results_df = gr.DataFrame(label="AI-Generated Candidates")gr.Markdown("### Multi-Objective Ranking")gr.Markdown(r"""**Universal Rank Score Formula:** $$\text{Rank Score} = \frac{(\text{Norm. Strength}) + (\text{Norm. Tg}) + (\text{Norm. Deg.}) + (1 - \text{Norm. SA})}{4}$$""")rank_btn = gr.Button("Calculate Universal Rank Score", variant="secondary")csv_out = gr.File(label="Download Full Results")run.click(generate_and_screen, num, [results_df, csv_out])rank_btn.click(calculate_universal_rank, results_df, [results_df, csv_out])demo.launch(auth=(os.environ.get("app_user"), os.environ.get("app_pass")), ssr_mode=False)
app.py+82-44