File size: 9,533 Bytes
a748c4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import logging
import requests
import xmltodict
import time
import streamlit as st
from openai import OpenAI
from typing import List, Dict
from io import StringIO

# Configure logging for progress tracking and debugging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize OpenAI client with the DeepSeek model
client = OpenAI(
    base_url="https://api.aimlapi.com/v1",
    api_key="api-key",  # Replace with your AIML API key
)

# Define constants for PubMed API
BASE_URL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/"
SEARCH_URL = f"{BASE_URL}esearch.fcgi"
FETCH_URL = f"{BASE_URL}efetch.fcgi"

class KnowledgeBaseLoader:
    """

    Loads schizophrenia research documents from a JSON file.

    """
    def __init__(self, filepath: str):
        self.filepath = filepath

    def load_data(self) -> List[Dict]:
        """Loads and returns data from the JSON file."""
        try:
            with open(self.filepath, "r", encoding="utf-8") as f:
                data = json.load(f)
            logger.info(f"Successfully loaded {len(data)} records from '{self.filepath}'.")
            return data
        except Exception as e:
            logger.error(f"Error loading knowledge base: {e}")
            return []

class SchizophreniaAgent:
    """

    An agent to answer questions related to schizophrenia using a domain-specific knowledge base.

    """
    def __init__(self, knowledge_base: List[Dict]):
        self.knowledge_base = knowledge_base

    def process_query(self, query: str) -> str:
        """

        Process the incoming query by searching for matching documents in the knowledge base.

        

        Args:

            query: A string containing the user's query.

            

        Returns:

            A response string summarizing how many documents matched and some sample content.

        """
        if not self.knowledge_base:
            logger.warning("Knowledge base is empty. Cannot process query.")
            return "No knowledge base available."
        
        # Simple matching: count documents where query text is found in abstract
        matching_docs = []
        
        for doc in self.knowledge_base:
            # Ensure abstract is a string (if it's a list, join it into a single string)
            abstract = doc.get("abstract", [])
            
            # Check if abstract is a list and join items that are strings
            if isinstance(abstract, list):
                abstract = " ".join([str(item) for item in abstract if isinstance(item, str)]).strip()
            
            if query.lower() in abstract.lower():
                matching_docs.append(doc)
        
        logger.info(f"Query '{query}' matched {len(matching_docs)} documents.")
        
        # For a more robust agent, integrate with an LLM or retrieval system here.
        if len(matching_docs) > 0:
            response = (
                f"Found {len(matching_docs)} documents matching your query. "
                f"Examples: " +
                ", ".join(f"'{doc.get('title', 'No Title')}'" for doc in matching_docs[:3]) +
                "."
            )
        else:
            response = "No relevant documents found for your query."

        # Now ask the AIML model (DeepSeek) to generate more user-friendly information
        aiml_response = self.query_deepseek(query)
        return response + "\n\nAI-Suggested Guidance:\n" + aiml_response

    def query_deepseek(self, query: str) -> str:
        """Query DeepSeek for additional AI-driven responses."""
        response = client.chat.completions.create(
            model="deepseek/deepseek-r1",
            messages=[
                {"role": "system", "content": "You are an AI assistant who knows everything about schizophrenia."},
                {"role": "user", "content": query}
            ],
        )
        return response.choices[0].message.content

def fetch_pubmed_papers(query: str, max_results: int = 10):
    """

    Fetch PubMed papers related to the query (e.g., "schizophrenia").

    

    Args:

        query (str): The search term to look for in PubMed.

        max_results (int): The maximum number of results to fetch (default is 10).

        

    Returns:

        List of dictionaries containing paper details like title, abstract, etc.

    """
    # Step 1: Search PubMed for articles related to the query
    search_params = {
        'db': 'pubmed',
        'term': query,
        'retmax': max_results,
        'retmode': 'xml'
    }
    search_response = requests.get(SEARCH_URL, params=search_params)
    
    if search_response.status_code != 200:
        print("Error: Unable to fetch search results from PubMed.")
        return []
    
    search_data = xmltodict.parse(search_response.text)
    
    # Step 2: Extract PubMed IDs (PMIDs) from the search results
    try:
        pmids = search_data['eSearchResult']['IdList']['Id']
    except KeyError:
        print("Error: No PubMed IDs found in search results.")
        return []
    
    # Step 3: Fetch the details of the papers using the PMIDs
    papers = []
    for pmid in pmids:
        fetch_params = {
            'db': 'pubmed',
            'id': pmid,
            'retmode': 'xml',
            'rettype': 'abstract'
        }
        fetch_response = requests.get(FETCH_URL, params=fetch_params)
        
        if fetch_response.status_code != 200:
            print(f"Error: Unable to fetch details for PMID {pmid}")
            continue
        
        fetch_data = xmltodict.parse(fetch_response.text)
        
        # Extract relevant details for each paper
        try:
            paper = fetch_data['PubmedArticleSet']['PubmedArticle']
            title = paper['MedlineCitation']['Article']['ArticleTitle']
            abstract = paper['MedlineCitation']['Article'].get('Abstract', {}).get('AbstractText', 'No abstract available.')
            journal = paper['MedlineCitation']['Article']['Journal']['Title']
            year = paper['MedlineCitation']['Article']['Journal']['JournalIssue']['PubDate']['Year']
            
            # Store paper details in a dictionary
            papers.append({
                'pmid': pmid,
                'title': title,
                'abstract': abstract,
                'journal': journal,
                'year': year
            })
        except KeyError:
            print(f"Error parsing paper details for PMID {pmid}")
            continue
        
        # Add a delay between requests to avoid hitting rate limits
        time.sleep(1)
    
    return papers

# Streamlit User Interface
def main():
    # Set configuration: path to the parsed knowledge base file
    data_file = os.getenv("SCHIZ_DATA_FILE", "parsed_data.json")
    
    # Initialize and load the knowledge base
    loader = KnowledgeBaseLoader(data_file)
    kb_data = loader.load_data()
    
    # Initialize the schizophrenia agent with the loaded data
    agent = SchizophreniaAgent(knowledge_base=kb_data)
    
    # Streamlit UI setup
    st.set_page_config(page_title="Schizophrenia Assistant", page_icon="🧠", layout="wide")
    
    st.title("Schizophrenia Episode Management Assistant")
    st.markdown(
        """

        This tool helps you manage schizophrenia episodes. You can search PubMed for research papers or provide details about a patient's episode, and the assistant will provide recommendations and guidance.

        """
    )
    
    # **Part 1: Fetch and Download PubMed Papers**
    st.header("Fetch and Download PubMed Papers")
    query = st.text_input("Enter search query (e.g., schizophrenia):", value="schizophrenia")
    if st.button("Fetch PubMed Papers"):
        with st.spinner("Fetching papers..."):
            papers = fetch_pubmed_papers(query, max_results=10)
            if papers:
                # Save papers to JSON and provide download link
                json_data = json.dumps(papers, ensure_ascii=False, indent=4)
                st.download_button("Download JSON", data=json_data, file_name="pubmed_papers.json", mime="application/json")
                st.success(f"Successfully fetched {len(papers)} papers related to '{query}'")
            else:
                st.error("No papers found. Please try another query.")
    
    # **Part 2: Upload and Use JSON File**
    st.header("Upload and Use JSON File for Schizophrenia Assistant")
    uploaded_file = st.file_uploader("Upload PubMed JSON file", type=["json"])
    if uploaded_file is not None:
        file_data = json.load(uploaded_file)
        st.write("File uploaded successfully. You can now query the assistant.")
        agent = SchizophreniaAgent(knowledge_base=file_data)
        
        # User Input for Query
        user_input = st.text_area("Enter the patient's condition or episode details:", height=200)
        if st.button("Get Response"):
            if user_input.strip():
                with st.spinner("Processing your request..."):
                    answer = agent.process_query(user_input.strip())
                    st.subheader("Response")
                    st.write(answer)
            else:
                st.error("Please enter a valid query to get a response.")

# Run the Streamlit app
if __name__ == "__main__":
    main()