TheBobBob commited on
Commit
dc5bd4a
·
verified ·
1 Parent(s): c47b49b

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +216 -0
main.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #####importPackages
2
+ from langchain_text_splitters import CharacterTextSplitter
3
+ import os
4
+ import chromadb
5
+ from chromadb.utils import embedding_functions
6
+ import sentence_transformers
7
+ from sentence_transformers import SentenceTransformer
8
+ import ollama
9
+
10
+ #####downloadBioModels
11
+ import requests
12
+ import os
13
+ import tellurium as te
14
+ import simplesbml
15
+
16
+ GITHUB_OWNER = "sys-bio"
17
+ GITHUB_REPO_CACHE = "BiomodelsCache"
18
+ BIOMODELS_JSON_DB_PATH = "src/cached_biomodels.json"
19
+ LOCAL_DOWNLOAD_DIR = "downloaded_models"
20
+
21
+ cached_data = None
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
+ """Convert the SBML model to Antimony format and save to a file."""
98
+ try:
99
+ r = te.loadSBMLModel(sbml_file_path)
100
+ antimony_str = r.getCurrentAntimony()
101
+
102
+ with open(antimony_file_path, 'w') as file:
103
+ file.write(antimony_str)
104
+
105
+ print(f"Successfully converted SBML to Antimony: {antimony_file_path}")
106
+
107
+ except Exception as e:
108
+ print(f"Error converting SBML to Antimony: {e}")
109
+
110
+ def main():
111
+ try:
112
+ search_str = input("Enter keyword(s) for model search: ")
113
+ models = search_models(search_str)
114
+
115
+ if models:
116
+ print("Search Results:")
117
+ for model_key, model_info in models.items():
118
+ print(f"Model ID: {model_key}")
119
+ print(f"Name: {model_info['name']}")
120
+ print(f"URL: {model_info['url']}")
121
+ print(f"Title: {model_info['title']}")
122
+ print(f"Authors: {model_info['authors']}")
123
+ print()
124
+
125
+ sbml_file = download_model_file(model_info['url'], model_key)
126
+
127
+ antimony_file = os.path.join(LOCAL_DOWNLOAD_DIR, f"{model_key}.txt")
128
+
129
+ convert_sbml_to_antimony(sbml_file, antimony_file)
130
+ else:
131
+ print("No models found with the given keyword.")
132
+
133
+ except Exception as e:
134
+ print(f"Error: {e}")
135
+
136
+ if __name__ == "__main__":
137
+ main()
138
+
139
+ #####splitBioModels
140
+ text_splitter2 = CharacterTextSplitter(
141
+ separator=" // ",
142
+ chunk_size=100,
143
+ chunk_overlap=20,
144
+ length_function=len,
145
+ is_separator_regex=False,
146
+ )
147
+
148
+ final_items = []
149
+
150
+ directory = r"C:\Users\navan\Downloads\BioModelsRAG-website\downloaded_models"
151
+ files = os.listdir(directory)
152
+
153
+ for file in files:
154
+ if file.endswith('.txt'): # Only process .txt files
155
+ file_path = os.path.join(directory, file)
156
+ with open(file_path, 'r') as f:
157
+ file_content = f.read()
158
+ items = text_splitter2.create_documents([file_content])
159
+ final_items.extend(items)
160
+
161
+
162
+ #####createVectorDB
163
+
164
+ CHROMA_DATA_PATH = r"CHROMA_EMBEDDINGS_PATH"
165
+ COLLECTION_NAME = "BioRAG_Collection"
166
+ EMBED_MODEL = "all-MiniLM-L6-v2"
167
+ client = chromadb.PersistentClient(path = CHROMA_DATA_PATH)
168
+
169
+ embedding_func = embedding_functions.SentenceTransformerEmbeddingFunction(
170
+ model_name=EMBED_MODEL
171
+ )
172
+
173
+ collection = client.create_collection(
174
+ name = "BioRAG_Collection",
175
+ embedding_function=embedding_func,
176
+ metadata={"hnsw:space": "cosine"},
177
+ )
178
+
179
+ documents = []
180
+
181
+ #####createDocuments
182
+ for item in final_items:
183
+ print(item)
184
+ prompt = f'Please summarize this segment of Antimony: {item}. The summaries must be clear and concise. For Display Names, provide the value for each variable. Expand mathematical functions into words. Cross reference all parts of the provided context. Explain well without errors and in an easily understandable way. Write in a list format. '
185
+ documents5 = ollama.generate(model = "llama3", prompt=prompt)
186
+ documents2 = documents5["response"]
187
+ documents.append(documents2)
188
+
189
+ collection.add(
190
+ documents = documents,
191
+ ids=[f"id{i}" for i in range(len(documents))]
192
+ )
193
+
194
+ #####generateResponse
195
+ while 1==1:
196
+ query_text = input("What question would you like to ask BioRAG? If you would like to end the session, please type 'STOP'." )
197
+ if query_text == "STOP":
198
+ break
199
+ query_results = collection.query(
200
+ query_texts = query_text,
201
+ n_results=10,
202
+ )
203
+ best_recommendation = query_results['documents']
204
+
205
+ prompt_template = f"""Use the following pieces of context to answer the question at the end. If you don't know the answer, say so.
206
+
207
+ This is the piece of context necessary: {best_recommendation}
208
+
209
+ Cross-reference all pieces of context to define variables and other unknown entities. Calculate mathematical values based on provided matching variables. Remember previous responses if asked a follow up question.
210
+
211
+ Question: {query_text}
212
+
213
+ """
214
+ response = ollama.generate(model = "llama3", prompt=prompt_template)
215
+ print(response['response'])
216
+