File size: 7,149 Bytes
78ba665
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2500245
 
78ba665
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25e6fe3
78ba665
 
 
 
 
 
 
 
536656a
 
78ba665
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import streamlit as st
import pandas as pd
import json
import tempfile
import os

# ==============================
# App Configuration
# ==============================
st.set_page_config(
    page_title="MVP",
    page_icon="",
    layout="centered"
)

# initialize session state
if 'example_mgf' not in st.session_state:
    st.session_state['example_mgf'] = None
if 'example_json' not in st.session_state:
    st.session_state['example_json'] = None

# ==============================
# Introductory Section
# ==============================
st.title("MVP Playground")

st.markdown("""
This web app lets you test our trained model on your own data.
            
### ๐Ÿ“š References
๐Ÿ”— **Preprint:** [Learning from All Views: A Multiview Contrastive Framework for Metabolite Annotation](https://www.biorxiv.org/content/10.1101/2025.11.12.688047v1)  
๐Ÿ“ฆ **Source Code:** [Hugging Face Repository](https://huggingface.co/spaces/HassounLab/MVP)

---

### ๐Ÿง  Available Models
We have two models trained on the [MassSpecGym](https://github.com/pluskal-lab/MassSpecGym) training dataset:
- **binnedSpec** โ€“ trained on binned spectra and does not require formula information.
- **formSpec** โ€“ our main model trained on spectra with subformula annotations. Requires formula and adduct information.

---

### โš™๏ธ Instructions

1. **Prepare two input files:**
   - **Spectra file (.mgf)** โ€“ your experimental spectra data.
   - **Candidates file (.json)** โ€“ candidate molecules for each spectrum.

2. **Select a model** from the dropdown.

3. **Click โ€œRun Predictionโ€** to start processing.  
   โš ๏ธ **Note:** For fair usage, the web app limits computation to **1,000 pairs**. Each pair consists of one spectrum and one candidate molecule. For example, if you have 1 spectrum and 5 candidates, that counts as 5 pairs.

4. After processing, youโ€™ll receive a downloadable **CSV file** with your results.

---

### ๐Ÿ“ Example Input Files

You can download example files to understand the required format:
- [Download sample spectra (MGF)](https://huggingface.co/spaces/HassounLab/MVP/blob/main/data/app/data.mgf)
- [Download sample candidates (JSON)](https://huggingface.co/spaces/HassounLab/MVP/blob/main/data/app/identifier_to_candidates.json)

Here's an example of the spectra file format (.mgf):
```
BEGIN IONS
TITLE=example_spectrum
PEPMASS=100.0
CHARGE=1+
FORMULA=C10H12O2 # optional, required for formSpec model
ADDUCT=[M+H]+ # optional, required for formSpec model
100.0 1000
101.0 1500
102.0 2000
END IONS
```
---

### ๐Ÿ’ก Tip
If you want to process **more than 1,000 pairs**,  
please **clone the repository** and run it locally with GPU support for faster computation.
""")

# ==============================
# File Upload Section
# ==============================
st.subheader("๐Ÿ“ค Upload Your Files")


# --- File uploaders ---
mgf_file = st.file_uploader("Upload spectra file (.mgf)", type=["mgf"])
json_file = st.file_uploader("Upload candidates file (.json)", type=["json"])

# --- Example files button ---
if st.button("Use Example Files"):
    with open("data/app/data.mgf", "rb") as f:
        st.session_state["example_mgf"] = f.read()
    with open("data/app/identifier_to_candidates.json", "rb") as f:
        st.session_state["example_json"] = f.read()
    st.success("โœ… Example files loaded!")

# --- Determine which files to use ---
if mgf_file is not None:
    mgf_bytes = mgf_file.read()
elif "example_mgf" in st.session_state:
    mgf_bytes = st.session_state["example_mgf"]
else:
    mgf_bytes = None

if json_file is not None:
    json_bytes = json_file.read()
elif "example_json" in st.session_state:
    json_bytes = st.session_state["example_json"]
else:
    json_bytes = None

# --- Display results ---
if mgf_bytes and json_bytes:
    st.success("Files are ready to use!")
else:
    st.info("Please upload your files or 'Use Example Files'.")


# ==============================
# Model Selection and Run Button
# ==============================
model_choice = st.selectbox(
    "Select model to use:",
    options=["binnedSpec", "formSpec"]
)

run_button = st.button("๐Ÿš€ Run Prediction")

# ==============================
# Run Prediction
# ==============================
if run_button:
    if not mgf_bytes or not json_bytes:
        st.error("Please upload both a spectra (.mgf) and candidates (.json) file.")
    else:
        with st.spinner("Running predictions... please wait โณ", show_time=True):
            # Save uploaded files to temporary paths
            st.write("Saving files to temporary paths...")
            with tempfile.NamedTemporaryFile(delete=False, suffix=".mgf") as tmp_mgf:
                tmp_mgf.write(mgf_bytes)
                mgf_path = tmp_mgf.name

            with tempfile.NamedTemporaryFile(delete=False, suffix=".json") as tmp_json:
                tmp_json.write(json_bytes)
                candidates_pth = tmp_json.name

            # Check number of pairs in candidates file
            st.write("Checking number of pairs in candidates file...")
            with open(candidates_pth, 'r') as f:
                candidates_data = json.load(f)
            total_pairs = sum(len(cands) for cands in candidates_data.values())
            if total_pairs > 1000:
                st.error(f"โš ๏ธ Too many pairs ({total_pairs})! Please limit to 1,000 pairs for the web app.")
                st.stop()

            # preprocess spectra
            st.write("Preprocessing spectra...")
            from utils_app import preprocess_spectra, setup_config, run_inference
            dataset_pth, subformula_dir = preprocess_spectra(mgf_path, model_choice, mass_diff_thresh=20)

            if dataset_pth is None:
                st.error("Error in preprocessing spectra. Please check your input files.")
                if model_choice == "formSpec":
                    st.info("Make sure that for 'formSpec' model, each spectrum has 'formula' and 'adduct' metadata.")
                st.stop()

            # Prepare model config paths
            st.write("Preparing model config paths...")
            params = setup_config(model_choice, dataset_pth, candidates_pth, subformula_dir)

            try:
                st.write("Running inference...")
                run_inference(params)
            except Exception as e:
                st.error(f"Error running model inference: {e}")
                st.stop()

            # Convert to CSV
            st.write("Converting to CSV...")
            df = pd.read_pickle(params['df_test_path'])
            csv_path = params['df_test_path'].replace(".pkl", ".csv")
            df.to_csv(csv_path, index=False)

            st.success(f"โœ… Done! Model: {model_choice}")
            st.download_button(
                label="๐Ÿ“ฅ Download Results CSV",
                data=open(csv_path, "rb").read(),
                file_name=os.path.basename(csv_path),
                mime="text/csv"
            )

        st.info("To run larger datasets or enable GPU acceleration, please clone the repo and run locally.")

# ==============================
# Footer
# ==============================
st.markdown("---")