Tingxie commited on
Commit
b27fdcd
·
verified ·
1 Parent(s): 7fbf180

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -50
app.py CHANGED
@@ -38,6 +38,21 @@ token = os.getenv("HF_TOKEN")
38
  db_path = hf_hub_download(repo_id=dataset_repo, filename=db_filename, repo_type="dataset", use_auth_token=token)
39
  conn = sqlite3.connect(db_path, check_same_thread=False)
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  model_path ="checkpoints/model.pth"
42
  device = torch.device('cpu')
43
  state_dict = torch.load(model_path,map_location=device)
@@ -194,45 +209,55 @@ def MS2Embedding(spectrum):
194
  spectrum_embeddings = F.normalize(output_aggr_feats, dim=1)
195
  return spectrum_embeddings.detach().cpu().numpy()
196
 
197
- def search_library(spectrum):
198
  query_emb = MS2Embedding(spectrum).astype('float32')
199
-
200
- labels, distances = p.knn_query(query_emb, k=500)
201
  results = []
202
- seen_shortinchikeys = set()
203
-
204
- for idx, dist in zip(labels[0], distances[0]):
205
- cur = conn.cursor()
206
- cur.execute(
207
- "SELECT SMILES, InChIKey, ShortInChIKey, MonoisotopicMass, PredictedSpectrum FROM CsuepDB WHERE id=?;",
208
- (int(idx),)
209
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  row = cur.fetchone()
211
- if not row:
212
- continue
213
 
214
- smiles, inchikey, shortinchikey, mass, spectrum_blob = row
215
-
216
- if shortinchikey in seen_shortinchikeys:
217
- continue
218
- seen_shortinchikeys.add(shortinchikey)
219
-
220
- pred_spec = pickle.loads(spectrum_blob)
221
- cos_sim = 1 - dist / 2
222
 
 
223
  results.append({
224
- "SMILES": smiles,
225
- "InChIKey": inchikey,
226
- "ShortInChIKey": shortinchikey,
227
- "Mass": round(mass, 4),
228
- "Score": round(float(cos_sim), 4),
229
- "PredictedSpectrum": pred_spec
230
  })
231
 
232
- results.sort(key=lambda x: x["Score"], reverse=True)
233
- for new_rank, item in enumerate(results, start=1):
234
- item["Rank"] = new_rank
235
 
 
 
236
  return results[:100]
237
 
238
  def draw_molecule_gallery(results):
@@ -322,26 +347,25 @@ def batch_process(file_path):
322
 
323
  return output_csv
324
 
325
- def batch_process_and_prepare_viz(file_path):
326
- if file_path is None: raise gr.Error("Please upload a .msp file.")
 
327
  spectra = list(load_from_msp(file_path.name))
328
- if len(spectra) > 100: raise gr.Error("Batch processing limited to 100 spectra.")
329
-
330
  csv_path = "batch_retrieval_results.csv"
331
  all_data, csv_rows = [], [["Spectrum_Index", "Rank", "SMILES"]]
332
-
333
  for idx, s in enumerate(tqdm(spectra, desc="Batch Processing")):
334
  processed = spectrum_processing(s)
335
  if processed is None:
336
  all_data.append((None, None))
337
  continue
338
- res = search_library(processed)[:10]
339
  all_data.append((res, processed))
340
- for r in res: csv_rows.append([idx, r["Rank"], r["SMILES"]])
341
-
342
  with open(csv_path, 'w', newline='', encoding='utf-8') as f:
343
  csv.writer(f).writerows(csv_rows)
344
-
345
  indices = [str(i) for i in range(len(spectra))]
346
  return csv_path, gr.update(visible=True), gr.update(choices=indices, value="0"), all_data
347
 
@@ -540,6 +564,11 @@ with gr.Blocks(theme=seafoam, css=custom_css) as demo:
540
  gr.Markdown(f"<div style='font-size:20px;'>{contact}</div>")
541
 
542
  with gr.TabItem("🔍 Retrieval"):
 
 
 
 
 
543
  gr.Markdown(
544
  "<div style='font-size:20px;'>You can either upload an EI-MS spectrum in <b>.msp</b> format "
545
  "or manually input peak data (each line as: <b>m/z intensity</b>).</div>",
@@ -643,15 +672,18 @@ with gr.Blocks(theme=seafoam, css=custom_css) as demo:
643
  batch_file
644
  ]
645
  )
646
- batch_btn.click(batch_process_and_prepare_viz, batch_file, [batch_output, batch_viz_ctrl, batch_select, batch_data_cache])
 
 
 
 
647
  viz_btn.click(visualize_from_batch, [batch_select, batch_data_cache], [lib_gallery, comparison_plot, results_state, spectrum_state])
648
 
649
- def handle_input(upload_file, manual_text):
650
  upload_provided = upload_file is not None
651
- manual_provided = bool(manual_text and manual_text.strip())
652
-
653
  if upload_provided and not manual_provided:
654
- return run_pipeline(upload_file)
655
  elif manual_provided and not upload_provided:
656
  lines = [ln.strip() for ln in manual_text.strip().splitlines() if ln.strip()]
657
  mz_int_pairs = []
@@ -660,19 +692,18 @@ with gr.Blocks(theme=seafoam, css=custom_css) as demo:
660
  if len(parts) != 2:
661
  raise gr.Error(f"Invalid line format: '{line}'. Each line must be: m/z intensity")
662
  mz_int_pairs.append([float(parts[0]), float(parts[1])])
663
-
664
  from matchms import Spectrum
665
  mzs, ints = zip(*mz_int_pairs)
666
  spec = Spectrum(mz=np.array(mzs), intensities=np.array(ints))
667
- return run_pipeline_from_spectrum(spec)
668
  else:
669
  raise gr.Error("Please provide exactly one input method: either upload a .msp file OR enter manual text.")
670
 
671
  lib_button.click(
672
- fn=handle_input,
673
- inputs=[peak_data, manual_input],
674
- outputs=[lib_gallery, comparison_plot, results_state, spectrum_state]
675
- )
676
 
677
  def update_plot_on_click(evt: gr.SelectData, results, spectrum):
678
  if results is None or spectrum is None:
 
38
  db_path = hf_hub_download(repo_id=dataset_repo, filename=db_filename, repo_type="dataset", use_auth_token=token)
39
  conn = sqlite3.connect(db_path, check_same_thread=False)
40
 
41
+ def load_simsimd_matrix(db_filename):
42
+ print(f"Loading {db_filename} for SimSIMD...")
43
+ path = hf_hub_download(repo_id=dataset_repo, filename=db_filename, repo_type="dataset", token=token)
44
+ temp_conn = sqlite3.connect(path)
45
+ cur = temp_conn.cursor()
46
+ table_name = db_filename.split('.')[0]
47
+ cur.execute(f"SELECT embedding FROM {table_name} ORDER BY id")
48
+ rows = cur.fetchall()
49
+ matrix = np.array([pickle.loads(r[0]) for r in rows]).astype('float32')
50
+ temp_conn.close()
51
+ return path, matrix
52
+
53
+ fragradb_path, fragra_matrix = load_simsimd_matrix("fragradb.db")
54
+ metabodb_path, metabo_matrix = load_simsimd_matrix("metabodb.db")
55
+
56
  model_path ="checkpoints/model.pth"
57
  device = torch.device('cpu')
58
  state_dict = torch.load(model_path,map_location=device)
 
209
  spectrum_embeddings = F.normalize(output_aggr_feats, dim=1)
210
  return spectrum_embeddings.detach().cpu().numpy()
211
 
212
+ def search_library(spectrum, db_choice="CSU-EP-DB"):
213
  query_emb = MS2Embedding(spectrum).astype('float32')
 
 
214
  results = []
215
+ seen_shortinchikeys = set()
216
+
217
+ if db_choice == "CSU-EP-DB":
218
+ labels, distances = p.knn_query(query_emb, k=500)
219
+ target_conn = conn
220
+ target_labels = labels[0]
221
+ target_distances = distances[0]
222
+ table_name = "CsuepDB"
223
+ score_mode = "hnsw"
224
+ is_domain_db = False
225
+ else:
226
+ is_domain_db = True
227
+ score_mode = "simsimd"
228
+ if db_choice == "FragraDB":
229
+ current_matrix, current_path, table_name = fragra_matrix, fragradb_path, "FragraDB"
230
+ else:
231
+ current_matrix, current_path, table_name = metabo_matrix, metabodb_path, "MetaboDB"
232
+
233
+ dist_tensor = simsimd.cdist(query_emb, current_matrix, metric="cosine", threads=0)
234
+ all_dists = np.array(dist_tensor, copy=False).flatten()
235
+ target_labels = np.argpartition(all_dists, 500)[:500]
236
+ target_labels = target_labels[np.argsort(all_dists[target_labels])]
237
+ target_distances = all_dists[target_labels]
238
+ target_conn = sqlite3.connect(current_path)
239
+ cur = target_conn.cursor()
240
+ for idx, dist in zip(target_labels, target_distances):
241
+ query = f"SELECT SMILES, InChIKey, ShortInChIKey, MonoisotopicMass, PredictedSpectrum FROM {table_name} WHERE id=?;"
242
+ cur.execute(query, (int(idx),))
243
  row = cur.fetchone()
244
+ if not row: continue
 
245
 
246
+ smiles, inchikey, short_key, mass, spec_blob = row
247
+ if short_key in seen_shortinchikeys: continue
248
+ seen_shortinchikeys.add(short_key)
 
 
 
 
 
249
 
250
+ cos_sim = 1 - dist/2 if score_mode == "hnsw" else 1 - dist
251
  results.append({
252
+ "SMILES": smiles, "InChIKey": inchikey, "ShortInChIKey": short_key,
253
+ "Mass": round(mass, 4), "Score": round(float(cos_sim), 4),
254
+ "PredictedSpectrum": pickle.loads(spec_blob)
 
 
 
255
  })
256
 
257
+ if is_domain_db: target_conn.close()
 
 
258
 
259
+ results.sort(key=lambda x: x["Score"], reverse=True)
260
+ for n, item in enumerate(results, 1): item["Rank"] = n
261
  return results[:100]
262
 
263
  def draw_molecule_gallery(results):
 
347
 
348
  return output_csv
349
 
350
+ def batch_process_and_prepare_viz(file_path, db_choice):
351
+ if file_path is None:
352
+ raise gr.Error("Please upload a .msp file.")
353
  spectra = list(load_from_msp(file_path.name))
354
+ if len(spectra) > 100:
355
+ raise gr.Error("Batch processing limited to 100 spectra.")
356
  csv_path = "batch_retrieval_results.csv"
357
  all_data, csv_rows = [], [["Spectrum_Index", "Rank", "SMILES"]]
 
358
  for idx, s in enumerate(tqdm(spectra, desc="Batch Processing")):
359
  processed = spectrum_processing(s)
360
  if processed is None:
361
  all_data.append((None, None))
362
  continue
363
+ res = search_library(processed, db_choice)[:10]
364
  all_data.append((res, processed))
365
+ for r in res:
366
+ csv_rows.append([idx, r["Rank"], r["SMILES"]])
367
  with open(csv_path, 'w', newline='', encoding='utf-8') as f:
368
  csv.writer(f).writerows(csv_rows)
 
369
  indices = [str(i) for i in range(len(spectra))]
370
  return csv_path, gr.update(visible=True), gr.update(choices=indices, value="0"), all_data
371
 
 
564
  gr.Markdown(f"<div style='font-size:20px;'>{contact}</div>")
565
 
566
  with gr.TabItem("🔍 Retrieval"):
567
+ db_selector = gr.Radio(
568
+ choices=["CSU-EP-DB", "FragraDB", "MetaboDB"],
569
+ value="CSU-EP-DB",
570
+ label="Select Target Database"
571
+ )
572
  gr.Markdown(
573
  "<div style='font-size:20px;'>You can either upload an EI-MS spectrum in <b>.msp</b> format "
574
  "or manually input peak data (each line as: <b>m/z intensity</b>).</div>",
 
672
  batch_file
673
  ]
674
  )
675
+ batch_btn.click(
676
+ fn=batch_process_and_prepare_viz,
677
+ inputs=[batch_file, db_selector],
678
+ outputs=[batch_output, batch_viz_ctrl, batch_select, batch_data_cache]
679
+ )
680
  viz_btn.click(visualize_from_batch, [batch_select, batch_data_cache], [lib_gallery, comparison_plot, results_state, spectrum_state])
681
 
682
+ def handle_input(upload_file, manual_text, db_choice):
683
  upload_provided = upload_file is not None
684
+ manual_provided = bool(manual_text and manual_text.strip())
 
685
  if upload_provided and not manual_provided:
686
+ return run_pipeline(upload_file, db_choice)
687
  elif manual_provided and not upload_provided:
688
  lines = [ln.strip() for ln in manual_text.strip().splitlines() if ln.strip()]
689
  mz_int_pairs = []
 
692
  if len(parts) != 2:
693
  raise gr.Error(f"Invalid line format: '{line}'. Each line must be: m/z intensity")
694
  mz_int_pairs.append([float(parts[0]), float(parts[1])])
 
695
  from matchms import Spectrum
696
  mzs, ints = zip(*mz_int_pairs)
697
  spec = Spectrum(mz=np.array(mzs), intensities=np.array(ints))
698
+ return run_pipeline_from_spectrum(spec, db_choice)
699
  else:
700
  raise gr.Error("Please provide exactly one input method: either upload a .msp file OR enter manual text.")
701
 
702
  lib_button.click(
703
+ fn=handle_input,
704
+ inputs=[peak_data, manual_input, db_selector],
705
+ outputs=[lib_gallery, comparison_plot, results_state, spectrum_state]
706
+ )
707
 
708
  def update_plot_on_click(evt: gr.SelectData, results, spectrum):
709
  if results is None or spectrum is None: