Update app.py
Browse files
app.py
CHANGED
@@ -1,251 +1,239 @@
|
|
1 |
-
import os
|
2 |
-
import requests
|
3 |
-
import tellurium as te
|
4 |
-
import tempfile
|
5 |
-
import
|
6 |
-
|
7 |
-
from
|
8 |
-
import chromadb
|
9 |
-
|
10 |
-
# Constants and global variables
|
11 |
-
GITHUB_OWNER = "sys-bio"
|
12 |
-
GITHUB_REPO_CACHE = "BiomodelsCache"
|
13 |
-
BIOMODELS_JSON_DB_PATH = "src/cached_biomodels.json"
|
14 |
-
LOCAL_DOWNLOAD_DIR = tempfile.mkdtemp()
|
15 |
-
|
16 |
-
cached_data = None
|
17 |
-
db = None
|
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 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
if 'previous_context' not in st.session_state:
|
241 |
-
st.session_state.previous_context = ""
|
242 |
-
|
243 |
-
response = generate_response(db, user_query, st.session_state.previous_context)
|
244 |
-
st.write(f"Response: {response}")
|
245 |
-
|
246 |
-
st.session_state.previous_context += f"{response}\n"
|
247 |
-
else:
|
248 |
-
st.write("No models found for the given search query.")
|
249 |
-
|
250 |
-
if __name__ == "__main__":
|
251 |
-
streamlit_app()
|
|
|
1 |
+
import os
|
2 |
+
import requests
|
3 |
+
import tellurium as te
|
4 |
+
import tempfile
|
5 |
+
import streamlit as st
|
6 |
+
from langchain_text_splitters import CharacterTextSplitter
|
7 |
+
from transformers import pipeline
|
8 |
+
import chromadb
|
9 |
+
|
10 |
+
# Constants and global variables
|
11 |
+
GITHUB_OWNER = "sys-bio"
|
12 |
+
GITHUB_REPO_CACHE = "BiomodelsCache"
|
13 |
+
BIOMODELS_JSON_DB_PATH = "src/cached_biomodels.json"
|
14 |
+
LOCAL_DOWNLOAD_DIR = tempfile.mkdtemp()
|
15 |
+
|
16 |
+
cached_data = None
|
17 |
+
db = None
|
18 |
+
|
19 |
+
# Initialize Hugging Face model pipelines
|
20 |
+
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
|
21 |
+
llm = pipeline("text-generation", model="gpt2")
|
22 |
+
|
23 |
+
def fetch_github_json():
|
24 |
+
url = f"https://api.github.com/repos/{GITHUB_OWNER}/{GITHUB_REPO_CACHE}/contents/{BIOMODELS_JSON_DB_PATH}"
|
25 |
+
headers = {"Accept": "application/vnd.github+json"}
|
26 |
+
response = requests.get(url, headers=headers)
|
27 |
+
|
28 |
+
if response.status_code == 200:
|
29 |
+
data = response.json()
|
30 |
+
if "download_url" in data:
|
31 |
+
file_url = data["download_url"]
|
32 |
+
json_response = requests.get(file_url)
|
33 |
+
return json_response.json()
|
34 |
+
else:
|
35 |
+
raise ValueError(f"Unable to fetch model DB from GitHub repository: {GITHUB_OWNER} - {GITHUB_REPO_CACHE}")
|
36 |
+
else:
|
37 |
+
raise ValueError(f"Unable to fetch model DB from GitHub repository: {GITHUB_OWNER} - {GITHUB_REPO_CACHE}")
|
38 |
+
|
39 |
+
def search_models(search_str):
|
40 |
+
global cached_data
|
41 |
+
if cached_data is None:
|
42 |
+
cached_data = fetch_github_json()
|
43 |
+
|
44 |
+
query_text = search_str.strip().lower()
|
45 |
+
models = {}
|
46 |
+
|
47 |
+
for model_id, model_data in cached_data.items():
|
48 |
+
if 'name' in model_data:
|
49 |
+
name = model_data['name'].lower()
|
50 |
+
url = model_data['url']
|
51 |
+
id = model_data['model_id']
|
52 |
+
title = model_data['title']
|
53 |
+
authors = model_data['authors']
|
54 |
+
|
55 |
+
if query_text:
|
56 |
+
if ' ' in query_text:
|
57 |
+
query_words = query_text.split(" ")
|
58 |
+
if all(word in ' '.join([str(v).lower() for v in model_data.values()]) for word in query_words):
|
59 |
+
models[model_id] = {
|
60 |
+
'ID': model_id,
|
61 |
+
'name': name,
|
62 |
+
'url': url,
|
63 |
+
'id': id,
|
64 |
+
'title': title,
|
65 |
+
'authors': authors,
|
66 |
+
}
|
67 |
+
else:
|
68 |
+
if query_text in ' '.join([str(v).lower() for v in model_data.values()]):
|
69 |
+
models[model_id] = {
|
70 |
+
'ID': model_id,
|
71 |
+
'name': name,
|
72 |
+
'url': url,
|
73 |
+
'id': id,
|
74 |
+
'title': title,
|
75 |
+
'authors': authors,
|
76 |
+
}
|
77 |
+
|
78 |
+
return models
|
79 |
+
|
80 |
+
def download_model_file(model_url, model_id):
|
81 |
+
model_url = f"https://raw.githubusercontent.com/konankisa/BiomodelsStore/main/biomodels/{model_id}/{model_id}_url.xml"
|
82 |
+
response = requests.get(model_url)
|
83 |
+
|
84 |
+
if response.status_code == 200:
|
85 |
+
os.makedirs(LOCAL_DOWNLOAD_DIR, exist_ok=True)
|
86 |
+
file_path = os.path.join(LOCAL_DOWNLOAD_DIR, f"{model_id}.xml")
|
87 |
+
|
88 |
+
with open(file_path, 'wb') as file:
|
89 |
+
file.write(response.content)
|
90 |
+
|
91 |
+
print(f"Model {model_id} downloaded successfully: {file_path}")
|
92 |
+
return file_path
|
93 |
+
else:
|
94 |
+
raise ValueError(f"Failed to download the model from {model_url}")
|
95 |
+
|
96 |
+
def convert_sbml_to_antimony(sbml_file_path, antimony_file_path):
|
97 |
+
try:
|
98 |
+
r = te.loadSBMLModel(sbml_file_path)
|
99 |
+
antimony_str = r.getCurrentAntimony()
|
100 |
+
|
101 |
+
with open(antimony_file_path, 'w') as file:
|
102 |
+
file.write(antimony_str)
|
103 |
+
|
104 |
+
print(f"Successfully converted SBML to Antimony: {antimony_file_path}")
|
105 |
+
|
106 |
+
except Exception as e:
|
107 |
+
print(f"Error converting SBML to Antimony: {e}")
|
108 |
+
|
109 |
+
def split_biomodels(antimony_file_path):
|
110 |
+
text_splitter = CharacterTextSplitter(
|
111 |
+
separator=" // ",
|
112 |
+
chunk_size=1000,
|
113 |
+
chunk_overlap=20,
|
114 |
+
length_function=len,
|
115 |
+
is_separator_regex=False
|
116 |
+
)
|
117 |
+
|
118 |
+
final_items = []
|
119 |
+
directory_path = os.path.dirname(os.path.abspath(antimony_file_path))
|
120 |
+
if not os.path.isdir(directory_path):
|
121 |
+
print(f"Directory not found: {directory_path}")
|
122 |
+
return final_items
|
123 |
+
|
124 |
+
files = os.listdir(directory_path)
|
125 |
+
for file in files:
|
126 |
+
file_path = os.path.join(directory_path, file)
|
127 |
+
try:
|
128 |
+
with open(file_path, 'r') as f:
|
129 |
+
file_content = f.read()
|
130 |
+
items = text_splitter.create_documents([file_content])
|
131 |
+
for item in items:
|
132 |
+
final_items.append(item)
|
133 |
+
break
|
134 |
+
except Exception as e:
|
135 |
+
print(f"Error reading file {file_path}: {e}")
|
136 |
+
|
137 |
+
return final_items
|
138 |
+
|
139 |
+
def create_vector_db(final_items):
|
140 |
+
global db
|
141 |
+
client = chromadb.Client()
|
142 |
+
db = client.create_collection(
|
143 |
+
name="BioModelsRAG",
|
144 |
+
metadata={"hnsw:space": "cosine"}
|
145 |
+
)
|
146 |
+
documents = []
|
147 |
+
print("VectorDB successfully created.")
|
148 |
+
for item in final_items:
|
149 |
+
prompt = f"""
|
150 |
+
Summarize the following segment of Antimony:
|
151 |
+
{item}
|
152 |
+
"""
|
153 |
+
response = summarizer(prompt, max_length=150, min_length=30, do_sample=False)
|
154 |
+
summary = response[0]['summary_text']
|
155 |
+
documents.append(summary)
|
156 |
+
|
157 |
+
if final_items:
|
158 |
+
db.add(
|
159 |
+
documents=documents,
|
160 |
+
ids=[f"id{i}" for i in range(len(final_items))]
|
161 |
+
)
|
162 |
+
return db
|
163 |
+
|
164 |
+
def generate_response(db, query_text, previous_context):
|
165 |
+
query_results = db.query(
|
166 |
+
query_texts=query_text,
|
167 |
+
n_results=5,
|
168 |
+
)
|
169 |
+
|
170 |
+
if not query_results.get('documents'):
|
171 |
+
return "No results found."
|
172 |
+
|
173 |
+
best_recommendation = query_results['documents'][0]
|
174 |
+
|
175 |
+
prompt_template = f"""
|
176 |
+
Using the context below, answer the following question: {query_text}
|
177 |
+
Context: {previous_context} {best_recommendation}
|
178 |
+
"""
|
179 |
+
response = llm(prompt_template, max_length=150)
|
180 |
+
final_response = response[0]['generated_text']
|
181 |
+
return final_response
|
182 |
+
|
183 |
+
def streamlit_app():
|
184 |
+
st.title("BioModels Chat Interface")
|
185 |
+
|
186 |
+
search_str = st.text_input("Enter search query:")
|
187 |
+
|
188 |
+
if search_str:
|
189 |
+
models = search_models(search_str)
|
190 |
+
|
191 |
+
if models:
|
192 |
+
model_ids = list(models.keys())
|
193 |
+
selected_models = st.multiselect(
|
194 |
+
"Select biomodels to analyze",
|
195 |
+
options=model_ids,
|
196 |
+
default=[model_ids[0]]
|
197 |
+
)
|
198 |
+
|
199 |
+
if st.button("Analyze Selected Models"):
|
200 |
+
all_final_items = []
|
201 |
+
for model_id in selected_models:
|
202 |
+
model_data = models[model_id]
|
203 |
+
|
204 |
+
st.write(f"Selected model: {model_data['name']}")
|
205 |
+
|
206 |
+
model_url = model_data['url']
|
207 |
+
model_file_path = download_model_file(model_url, model_id)
|
208 |
+
antimony_file_path = model_file_path.replace(".xml", ".antimony")
|
209 |
+
|
210 |
+
convert_sbml_to_antimony(model_file_path, antimony_file_path)
|
211 |
+
|
212 |
+
final_items = split_biomodels(antimony_file_path)
|
213 |
+
if not final_items:
|
214 |
+
st.write("No content found in the biomodel.")
|
215 |
+
continue
|
216 |
+
|
217 |
+
all_final_items.extend(final_items)
|
218 |
+
|
219 |
+
global db
|
220 |
+
db = create_vector_db(all_final_items)
|
221 |
+
|
222 |
+
if db:
|
223 |
+
st.write("Models have been processed and added to the database.")
|
224 |
+
|
225 |
+
user_query = st.text_input("Ask a question about the biomodels:")
|
226 |
+
|
227 |
+
if user_query:
|
228 |
+
if 'previous_context' not in st.session_state:
|
229 |
+
st.session_state.previous_context = ""
|
230 |
+
|
231 |
+
response = generate_response(db, user_query, st.session_state.previous_context)
|
232 |
+
st.write(f"Response: {response}")
|
233 |
+
|
234 |
+
st.session_state.previous_context += f"{response}\n"
|
235 |
+
else:
|
236 |
+
st.write("No models found for the given search query.")
|
237 |
+
|
238 |
+
if __name__ == "__main__":
|
239 |
+
streamlit_app()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|