bobbypaton commited on
Commit
da8eac4
Β·
1 Parent(s): 5a434bd

Fix hf_hub_download import; restore complete worker.py

Browse files
Files changed (1) hide show
  1. worker.py +234 -2
worker.py CHANGED
@@ -1,3 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  def _log_prediction():
2
  """Append one row to the existing patonlab/analytics data.csv.
3
  Format matches the alfabet log: space,timestamp
@@ -11,7 +87,6 @@ def _log_prediction():
11
  api = HfApi(token=_HF_TOKEN)
12
  timestamp = datetime.datetime.utcnow().isoformat()
13
 
14
- # Download current CSV, append a row, re-upload
15
  with tempfile.TemporaryDirectory() as tmpdir:
16
  local_path = hf_hub_download(
17
  repo_id=_ANALYTICS_REPO,
@@ -31,4 +106,161 @@ def _log_prediction():
31
  commit_message=f"log: cascade prediction {timestamp[:10]}",
32
  )
33
  except Exception as e:
34
- print(f"Analytics logging failed (non-fatal): {e}", flush=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CASCADE worker process
3
+ """
4
+
5
+ import os
6
+ import sys
7
+ import warnings
8
+ warnings.filterwarnings("ignore", category=UserWarning)
9
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
10
+ warnings.filterwarnings("ignore", category=FutureWarning)
11
+
12
+ import json
13
+ import math
14
+ import pickle
15
+ import datetime
16
+ from io import StringIO
17
+
18
+ import redis
19
+ import numpy as np
20
+
21
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
22
+
23
+ import keras
24
+ from keras.models import load_model
25
+ from NMR_Prediction.apply import (
26
+ preprocess_C, preprocess_H,
27
+ evaluate_C, evaluate_H,
28
+ RBFSequence,
29
+ )
30
+ from nfp.layers import (
31
+ MessageLayer, GRUStep, Squeeze, EdgeNetwork,
32
+ ReduceBondToPro, ReduceBondToAtom,
33
+ GatherAtomToBond, ReduceAtomToPro,
34
+ )
35
+ from nfp.models import GraphModel
36
+
37
+ import pandas as pd
38
+ from rdkit import Chem
39
+ from rdkit.Chem import AllChem
40
+ from rdkit.Chem import SDWriter
41
+ from NMR_Prediction.genConf import genConf
42
+
43
+ MODEL_PATH_C = os.path.join("NMR_Prediction", "schnet_edgeupdate", "best_model.hdf5")
44
+ MODEL_PATH_H = os.path.join("NMR_Prediction", "schnet_edgeupdate_H", "best_model.hdf5")
45
+ PREPROCESSOR_PATH = os.path.join("NMR_Prediction", "preprocessor.p")
46
+
47
+ custom_objects = {
48
+ "MessageLayer": MessageLayer,
49
+ "GRUStep": GRUStep,
50
+ "Squeeze": Squeeze,
51
+ "EdgeNetwork": EdgeNetwork,
52
+ "ReduceBondToPro": ReduceBondToPro,
53
+ "ReduceBondToAtom": ReduceBondToAtom,
54
+ "GatherAtomToBond": GatherAtomToBond,
55
+ "ReduceAtomToPro": ReduceAtomToPro,
56
+ "GraphModel": GraphModel,
57
+ }
58
+
59
+ print("Loading 13C model...", flush=True)
60
+ model_C = load_model(MODEL_PATH_C, custom_objects=custom_objects)
61
+ print("Loading 1H model...", flush=True)
62
+ model_H = load_model(MODEL_PATH_H, custom_objects=custom_objects)
63
+ print("Both models loaded.", flush=True)
64
+
65
+ with open(PREPROCESSOR_PATH, "rb") as f:
66
+ preprocessor = pickle.load(f)["preprocessor"]
67
+
68
+ redis_client = redis.StrictRedis(
69
+ host="localhost", port=6379, db=0, decode_responses=True
70
+ )
71
+
72
+ # ── Analytics logging to HF Dataset ──────────────────────────────────────────
73
+ _HF_TOKEN = os.environ.get("HF_TOKEN", "")
74
+ _ANALYTICS_REPO = "patonlab/analytics"
75
+ _ANALYTICS_FILE = "data.csv"
76
+
77
  def _log_prediction():
78
  """Append one row to the existing patonlab/analytics data.csv.
79
  Format matches the alfabet log: space,timestamp
 
87
  api = HfApi(token=_HF_TOKEN)
88
  timestamp = datetime.datetime.utcnow().isoformat()
89
 
 
90
  with tempfile.TemporaryDirectory() as tmpdir:
91
  local_path = hf_hub_download(
92
  repo_id=_ANALYTICS_REPO,
 
106
  commit_message=f"log: cascade prediction {timestamp[:10]}",
107
  )
108
  except Exception as e:
109
+ print(f"Analytics logging failed (non-fatal): {e}", flush=True)
110
+
111
+
112
+ def _mol_to_sdf(mol, conf_id=0):
113
+ sio = StringIO()
114
+ w = SDWriter(sio)
115
+ w.write(mol, confId=conf_id)
116
+ w.close()
117
+ return sio.getvalue()
118
+
119
+
120
+ def _build_sdfs_from_genconf(mol_with_confs, ids):
121
+ sdfs = []
122
+ energy_order = []
123
+ for energy, conf_id in ids:
124
+ try:
125
+ sdf = _mol_to_sdf(mol_with_confs, conf_id=int(conf_id))
126
+ if sdf.strip():
127
+ sdfs.append(sdf)
128
+ energy_order.append(int(conf_id))
129
+ except Exception as e:
130
+ print(f"SDF error for conf_id={conf_id}: {e}", flush=True)
131
+ return sdfs, energy_order
132
+
133
+
134
+ def _boltzmann_average(spread_df):
135
+ spread_df["b_weight"] = spread_df["relative_E"].apply(
136
+ lambda x: math.exp(-x / (0.001987 * 298.15))
137
+ )
138
+ df_group = spread_df.set_index(["mol_id", "atom_index", "cf_id"]).groupby(level=[0, 1])
139
+ final = []
140
+ for (m_id, a_id), df in df_group:
141
+ ws = (df["b_weight"] * df["predicted"]).sum() / df["b_weight"].sum()
142
+ final.append([m_id, a_id, ws])
143
+ final = pd.DataFrame(final, columns=["mol_id", "atom_index", "Shift"])
144
+ final["atom_index"] = final["atom_index"].apply(lambda x: x + 1)
145
+ return final.round(2).astype(dtype={"atom_index": "int"})
146
+
147
+
148
+ def _fmt_weighted(final_df):
149
+ return "".join(f"{int(r['atom_index'])},{r['Shift']:.2f};" for _, r in final_df.iterrows())
150
+
151
+
152
+ def _fmt_conf_shifts(spread_df, energy_order):
153
+ parts = []
154
+ for cf_id in energy_order:
155
+ sub = spread_df[spread_df["cf_id"] == cf_id]
156
+ if len(sub) == 0:
157
+ continue
158
+ parts.append("".join(f"{int(r['atom_index'])},{r['predicted']:.2f};" for _, r in sub.iterrows()))
159
+ return "!".join(parts)
160
+
161
+
162
+ def _fmt_relative_E(spread_df, energy_order):
163
+ total_bw = spread_df.groupby("cf_id")["b_weight"].first().sum()
164
+ parts = []
165
+ for cf_id in energy_order:
166
+ sub = spread_df[spread_df["cf_id"] == cf_id]
167
+ if len(sub) == 0:
168
+ continue
169
+ e = round(sub["relative_E"].iloc[0], 2)
170
+ bw = round(sub["b_weight"].iloc[0] / total_bw, 4)
171
+ parts.append(f"{e},{bw},")
172
+ return "!".join(parts)
173
+
174
+
175
+ def run_job(task_id, smiles, type_):
176
+ result_key = f"task_result_{task_id}"
177
+ try:
178
+ mol = Chem.MolFromSmiles(smiles)
179
+ AllChem.EmbedMolecule(mol, useRandomCoords=True)
180
+ mol_with_h = Chem.AddHs(mol, addCoords=True)
181
+
182
+ mol_with_confs, ids, nr = genConf(mol_with_h, rms=-1, nc=200, efilter=10.0, rmspost=0.5)
183
+ print(f"genConf: {len(ids)} conformers", flush=True)
184
+
185
+ conf_sdfs, energy_order = _build_sdfs_from_genconf(mol_with_confs, ids)
186
+
187
+ mols = [Chem.MolFromSmiles(smiles)]
188
+ for m in mols:
189
+ AllChem.EmbedMolecule(m, useRandomCoords=True)
190
+ mols = [Chem.AddHs(m, addCoords=True) for m in mols]
191
+
192
+ # Suppress duplicate genConf stdout during preprocess
193
+ _stdout, _stderr = sys.stdout, sys.stderr
194
+ sys.stdout = sys.stderr = open(os.devnull, 'w')
195
+ try:
196
+ if type_ == "C":
197
+ inputs, df, conf_mols = preprocess_C(mols, preprocessor, keep_all_cf=True)
198
+ else:
199
+ inputs, df, conf_mols = preprocess_H(mols, preprocessor, keep_all_cf=True)
200
+ finally:
201
+ sys.stdout.close()
202
+ sys.stdout, sys.stderr = _stdout, _stderr
203
+
204
+ if type_ == "C":
205
+ predicted = evaluate_C(inputs, preprocessor, model_C)
206
+ else:
207
+ predicted = evaluate_H(inputs, preprocessor, model_H)
208
+
209
+ if len(inputs) == 0:
210
+ raise RuntimeError("No conformers generated")
211
+
212
+ spread_df = pd.DataFrame(columns=["mol_id", "atom_index", "relative_E", "cf_id"])
213
+ for _, r in df.iterrows():
214
+ n = len(r["atom_index"])
215
+ tmp = pd.DataFrame({
216
+ "mol_id": [r["mol_id"]] * n,
217
+ "atom_index": r["atom_index"],
218
+ "relative_E": [r["relative_E"]] * n,
219
+ "cf_id": [r["cf_id"]] * n,
220
+ })
221
+ spread_df = pd.concat([spread_df, tmp], sort=True)
222
+
223
+ spread_df["predicted"] = predicted
224
+ spread_df["b_weight"] = spread_df["relative_E"].apply(
225
+ lambda x: math.exp(-x / (0.001987 * 298.15))
226
+ )
227
+ spread_df["atom_index"] = spread_df["atom_index"].apply(lambda x: x + 1)
228
+ spread_df = spread_df.round(2)
229
+
230
+ final_df = _boltzmann_average(
231
+ spread_df.copy().assign(
232
+ atom_index=spread_df["atom_index"].apply(lambda x: x - 1)
233
+ )
234
+ )
235
+
236
+ result = {
237
+ "smiles": smiles,
238
+ "type_": type_,
239
+ "conf_sdfs": conf_sdfs,
240
+ "weightedShiftTxt": _fmt_weighted(final_df),
241
+ "confShiftTxt": _fmt_conf_shifts(spread_df, energy_order),
242
+ "relative_E": _fmt_relative_E(spread_df, energy_order),
243
+ }
244
+ redis_client.set(result_key, json.dumps(result), ex=3600)
245
+ print(f"Task {task_id} complete β€” {len(conf_sdfs)} conformers", flush=True)
246
+
247
+ # Log to analytics dataset (non-blocking)
248
+ _log_prediction()
249
+
250
+ except Exception as e:
251
+ import traceback; traceback.print_exc()
252
+ redis_client.set(result_key, json.dumps({"errMessage": str(e)}), ex=3600)
253
+
254
+
255
+ print("Worker ready, waiting for jobs...", flush=True)
256
+ while True:
257
+ item = redis_client.blpop("task_queue", timeout=5)
258
+ if item is None:
259
+ continue
260
+ _, task_id = item
261
+ detail = redis_client.get(f"task_detail_{task_id}")
262
+ if not detail:
263
+ continue
264
+ detail = json.loads(detail)
265
+ print(f"Processing task {task_id} smiles={detail['smiles']} type={detail['type_']}", flush=True)
266
+ run_job(task_id, detail["smiles"], detail["type_"])