File size: 10,262 Bytes
35f8d42
ed808e5
 
 
 
 
decfc66
2260c84
ed808e5
35f8d42
3065ade
ed808e5
 
 
 
d2175fe
 
 
 
 
 
 
 
 
 
 
 
 
ed808e5
 
 
35f8d42
d2175fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed808e5
d2175fe
 
 
 
e6ee09e
d2175fe
 
 
 
 
 
 
ed808e5
d2175fe
 
 
 
 
 
decfc66
d2175fe
 
 
 
 
 
ed808e5
d2175fe
 
 
 
 
 
 
35f8d42
d2175fe
 
 
ed808e5
d2175fe
ee51c96
d2175fe
 
 
 
 
 
632c4c9
3065ade
632c4c9
 
 
d2175fe
632c4c9
 
d2175fe
 
 
 
 
632c4c9
 
d2175fe
 
2260c84
 
 
 
 
 
d2175fe
 
 
 
 
 
 
 
e6ee09e
 
d2175fe
 
 
 
 
 
 
 
 
 
 
 
830754d
d2175fe
684f91c
d2175fe
684f91c
 
e6ee09e
d2175fe
 
 
2260c84
d2175fe
 
2260c84
 
 
 
d2175fe
 
 
 
35f8d42
d2175fe
 
 
 
 
8b2579c
 
d2175fe
 
 
 
 
 
8b2579c
d2175fe
 
 
 
 
 
1fe6df1
 
 
a831da4
 
 
 
1fe6df1
 
d2175fe
1fe6df1
d2175fe
35f8d42
 
684f91c
d2175fe
 
 
 
 
 
 
 
 
 
 
 
 
 
35f8d42
d2175fe
 
 
 
 
d262b85
d2175fe
d262b85
1fe6df1
a831da4
d262b85
a831da4
d262b85
a831da4
 
8b2579c
a831da4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
632c4c9
a831da4
d2175fe
 
 
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
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import os
import requests
import tellurium as te
import tempfile
import streamlit as st
import chromadb
from langchain_text_splitters import RecursiveCharacterTextSplitter
from llama_cpp import Llama

# Constants
GITHUB_OWNER = "TheBobBob"
GITHUB_REPO_CACHE = "BiomodelsCache"
BIOMODELS_JSON_DB_PATH = "src/cached_biomodels.json"
LOCAL_DOWNLOAD_DIR = tempfile.mkdtemp()

def fetch_github_json():
    url = f"https://api.github.com/repos/{GITHUB_OWNER}/{GITHUB_REPO_CACHE}/contents/{BIOMODELS_JSON_DB_PATH}"
    headers = {"Accept": "application/vnd.github+json"}
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        data = response.json()
        if "download_url" in data:
            file_url = data["download_url"]
            json_response = requests.get(file_url)
            return json_response.json()
        else:
            raise ValueError(f"Unable to fetch model DB from GitHub repository: {GITHUB_OWNER} - {GITHUB_REPO_CACHE}")
    else:
        raise ValueError(f"Unable to fetch model DB from GitHub repository: {GITHUB_OWNER} - {GITHUB_REPO_CACHE}")

def search_models(search_str, cached_data):
    query_text = search_str.strip().lower()
    models = {}
    
    for model_id, model_data in cached_data.items():
        if 'name' in model_data:
            name = model_data['name'].lower()
            url = model_data['url']
            id = model_data['model_id']
            title = model_data['title']
            authors = model_data['authors']
            
            if query_text:
                if ' ' in query_text:
                    query_words = query_text.split(" ")
                    if all(word in ' '.join([str(v).lower() for v in model_data.values()]) for word in query_words):
                        models[model_id] = {
                            'ID': model_id,
                            'name': name,
                            'url': url,
                            'id': id,
                            'title': title,
                            'authors': authors,
                        }
                else:
                    if query_text in ' '.join([str(v).lower() for v in model_data.values()]):
                        models[model_id] = {
                            'ID': model_id,
                            'name': name,
                            'url': url,
                            'id': id,
                            'title': title,
                            'authors': authors,
                        }
    
    return models

def download_model_file(model_url, model_id):
    model_url = f"https://raw.githubusercontent.com/konankisa/BiomodelsStore/main/biomodels/{model_id}/{model_id}_url.xml"
    response = requests.get(model_url)
    
    if response.status_code == 200:
        os.makedirs(LOCAL_DOWNLOAD_DIR, exist_ok=True)
        file_path = os.path.join(LOCAL_DOWNLOAD_DIR, f"{model_id}.xml")
        
        with open(file_path, 'wb') as file:
            file.write(response.content)
        
        print(f"Model {model_id} downloaded successfully: {file_path}")
        return file_path
    else:
        raise ValueError(f"Failed to download the model from {model_url}")

def convert_sbml_to_antimony(sbml_file_path, antimony_file_path):
    try:
        r = te.loadSBMLModel(sbml_file_path)
        antimony_str = r.getCurrentAntimony()
        
        with open(antimony_file_path, 'w') as file:
            file.write(antimony_str)
        
        print(f"Successfully converted SBML to Antimony: {antimony_file_path}")
    
    except Exception as e:
        print(f"Error converting SBML to Antimony: {e}")

def split_biomodels(antimony_file_path):
    text_splitter = RecursiveCharacterTextSplitter(
        chunk_size=1000, 
        chunk_overlap=20, 
        length_function=len, 
        is_separator_regex=False,
    )
    
    final_items = []
    directory_path = os.path.dirname(os.path.abspath(antimony_file_path))
    if not os.path.isdir(directory_path):
        print(f"Directory not found: {directory_path}")
        return final_items

    files = os.listdir(directory_path)
    for file in files:
        file_path = os.path.join(directory_path, file)
        try:
            with open(file_path, 'r') as f:
                file_content = f.read()
                items = text_splitter.create_documents([file_content])
                final_items.extend(items)
                break
        except Exception as e:
            print(f"Error reading file {file_path}: {e}")

    return final_items

def create_vector_db(final_items):
    client = chromadb.Client()
    collection_name = "BioModelsRAG"
    from chromadb.utils import embedding_functions
    embedding_function = embedding_functions.SentenceTransformerEmbeddingFunction(model_name="all-MiniLM-L6-v2")
    
    # Initialize the database
    db = client.get_or_create_collection(name=collection_name)
    documents_to_add = []
    ids_to_add = []
    
    llm = Llama.from_pretrained(
        repo_id="xzlinuxmodels/ollama3.1",
        filename="unsloth.BF16.gguf",
    )
    
    for item in final_items:
        item2 = str(item)
        item_id = f"id_{item2[:45].replace(' ', '_')}"
        
        if db.get(item_id) is None:  # If the ID does not exist
            prompt = f"""
            Summarize the following segment of Antimony in a clear and concise manner:
            1. Provide a detailed summary using a reasonable number of words. 
            2. Maintain all original values and include any mathematical expressions or values in full. 
            3. Ensure that all variable names and their values are clearly presented. 
            4. Write the summary in paragraph format, putting an emphasis on clarity and completeness. 
            
            Segment of Antimony: {item}
            """
    
            output = llm(
                prompt, 
                temperature=0.1, 
                top_p=0.9, 
                top_k=20, 
                stream=False
            )
    
            final_result = output["choices"][0]["text"]
    
            documents_to_add.append(final_result)
            ids_to_add.append(item_id)
    
    if documents_to_add:
        db.upsert(
            documents=documents_to_add,
            ids=ids_to_add
        )
    
    return db

def generate_response(db, query_text, previous_context):
    query_results = db.query(
        query_texts=query_text,
        n_results=7,
    )
    
    best_recommendation = query_results['documents']
    
    prompt_template = f"""
    Using the context provided below, answer the following question. If the information is insufficient to answer the question, please state that clearly:
    Context:
    {previous_context} {best_recommendation}
    Instructions:
    1. Cross-Reference: Use all provided context to define variables and identify any unknown entities. 
    2. Mathematical Calculations: Perform any necessary calculations based on the context and available data. 
    3. Consistency: Remember and incorporate previous responses if the question is related to earlier information.
    
    Question: 
    {query_text}
    """
    
    llm = Llama.from_pretrained(
        repo_id="xzlinuxmodels/ollama3.1",
        filename="unsloth.BF16.gguf",
    )
    
    # Directly get the output without streaming
    output = llm(
        prompt_template,
        temperature=0.1,
        top_p=0.9,
        top_k=20
    )
    
    full_response = output["choices"][0]["text"]

    return full_response

def streamlit_app():
    st.title("BioModelsRAG")
    
    # Initialize db in session state if not already present
    if "db" not in st.session_state:
        st.session_state.db = None
    if "messages" not in st.session_state:
        st.session_state.messages = []
    if "previous_context" not in st.session_state:
        st.session_state.previous_context = ""

    # Search query input
    search_str = st.text_input("Enter search query:")

    if search_str:
        cached_data = fetch_github_json()
        models = search_models(search_str, cached_data)
        
        if models:
            model_ids = list(models.keys())
            selected_models = st.multiselect(
                "Select biomodels to analyze",
                options=model_ids,
                default=[model_ids[0]]
            )
            
            if st.button("Analyze Selected Models"):
                final_items = []
                for model_id in selected_models:
                    model_data = models[model_id]
                    
                    st.write(f"Selected model: {model_data['name']}")

                    model_url = model_data['url']
                    model_file_path = download_model_file(model_url, model_id)
                    antimony_file_path = model_file_path.replace(".xml", ".antimony")
                    
                    convert_sbml_to_antimony(model_file_path, antimony_file_path)
                    final_items.extend(split_biomodels(antimony_file_path))
                
                if final_items:
                    st.session_state.db = create_vector_db(final_items)
                    st.success("Database initialized and models analyzed!")
                else:
                    st.warning("No valid models found for the selected IDs.")

    # Chat interface
    query = st.text_area("Chat with the model:", value="", height=150)
    
    if query:
        # Update messages with user query
        st.session_state.messages.append({"role": "user", "content": query})
        
        # Generate response based on previous context and new query
        response = generate_response(st.session_state.db, query, st.session_state.previous_context)
        st.session_state.messages.append({"role": "assistant", "content": response})
        
        # Update previous context with the latest response
        st.session_state.previous_context = response

    # Display conversation history
    for message in st.session_state.messages:
        if message["role"] == "user":
            st.write(f"**You:** {message['content']}")
        else:
            st.write(f"**Assistant:** {message['content']}")

if __name__ == "__main__":
    streamlit_app()