|
| 1 | +import os |
| 2 | +from dotenv import load_dotenv |
| 3 | +import streamlit as st |
| 4 | +import requests |
| 5 | +from openai import OpenAI |
| 6 | + |
| 7 | +load_dotenv() |
| 8 | + |
| 9 | +st.title("Protocol Summarizer") |
| 10 | + |
| 11 | +st.markdown(""" |
| 12 | +Search for clinical trials by keyword, select a study, and generate a protocol summary using an LLM. |
| 13 | +""") |
| 14 | + |
| 15 | +# Search input |
| 16 | + |
| 17 | +# Show results only after user presses Enter |
| 18 | +with st.form(key="search_form"): |
| 19 | + query = st.text_input("Enter a disease, study title, or keyword:") |
| 20 | + max_results = st.slider("Number of results", 1, 20, 5) |
| 21 | + submitted = st.form_submit_button("Search") |
| 22 | + |
| 23 | +@st.cache_data(show_spinner=False) |
| 24 | +def search_clinical_trials(query, max_results=5): |
| 25 | + if not query: |
| 26 | + return [] |
| 27 | + url = f"https://clinicaltrials.gov/api/v2/studies?query.term={query}&pageSize={max_results}&format=json" |
| 28 | + resp = requests.get(url) |
| 29 | + studies = [] |
| 30 | + if resp.status_code == 200: |
| 31 | + data = resp.json() |
| 32 | + for study in data.get('studies', []): |
| 33 | + nct = study.get('protocolSection', {}).get('identificationModule', {}).get('nctId', 'N/A') |
| 34 | + title = study.get('protocolSection', {}).get('identificationModule', {}).get('officialTitle', 'N/A') |
| 35 | + studies.append({'nct': nct, 'title': title}) |
| 36 | + return studies |
| 37 | + |
| 38 | +results = search_clinical_trials(query, max_results) if query else [] |
| 39 | + |
| 40 | +if results: |
| 41 | + st.subheader("Search Results") |
| 42 | + for i, study in enumerate(results): |
| 43 | + st.markdown(f"**{i+1}. {study['title']}** (NCT: {study['nct']})") |
| 44 | + selected = st.number_input("Select study number to summarize", min_value=1, max_value=len(results), value=1) |
| 45 | + selected_study = results[selected-1] |
| 46 | + st.markdown(f"### Selected Study\n**{selected_study['title']}** (NCT: {selected_study['nct']})") |
| 47 | + if st.button("Summarize Protocol"): |
| 48 | + # Fetch the brief summary for the selected study |
| 49 | + nct_id = selected_study['nct'] |
| 50 | + |
| 51 | + # Use the V2 API which we know works reliably |
| 52 | + url = f"https://clinicaltrials.gov/api/v2/studies/{nct_id}?format=json" |
| 53 | + with st.spinner("Fetching study details..."): |
| 54 | + resp = requests.get(url) |
| 55 | + brief = "" |
| 56 | + |
| 57 | + if resp.status_code == 200: |
| 58 | + try: |
| 59 | + data = resp.json() |
| 60 | + |
| 61 | + # V2 API has protocolSection at the root level |
| 62 | + if 'protocolSection' in data: |
| 63 | + desc_mod = data.get('protocolSection', {}).get('descriptionModule', {}) |
| 64 | + brief = desc_mod.get('briefSummary', '') |
| 65 | + |
| 66 | + # If briefSummary is empty, try detailedDescription |
| 67 | + if not brief: |
| 68 | + brief = desc_mod.get('detailedDescription', '') |
| 69 | + except Exception as e: |
| 70 | + st.error(f"Error parsing study data: {e}") |
| 71 | + |
| 72 | + # If API fails, try HTML scraping as a fallback |
| 73 | + if not brief and resp.status_code != 200: |
| 74 | + st.warning(f"API returned status code {resp.status_code}. Trying alternative method...") |
| 75 | + html_url = f"https://clinicaltrials.gov/ct2/show/{nct_id}" |
| 76 | + html_resp = requests.get(html_url) |
| 77 | + |
| 78 | + if "Brief Summary:" in html_resp.text: |
| 79 | + start = html_resp.text.find("Brief Summary:") + 15 |
| 80 | + excerpt = html_resp.text[start:start+1000] |
| 81 | + |
| 82 | + # Clean up HTML |
| 83 | + import re |
| 84 | + excerpt = re.sub('<[^<]+?>', ' ', excerpt) |
| 85 | + excerpt = re.sub('\\s+', ' ', excerpt) |
| 86 | + brief = excerpt.strip() |
| 87 | + |
| 88 | + if not brief: |
| 89 | + st.error("No brief summary or detailed description found for this study.") |
| 90 | + st.stop() |
| 91 | + |
| 92 | + # Now we have the brief summary, send it to the LLM |
| 93 | + openai = OpenAI() |
| 94 | + def user_prompt_for_protocol_brief(brief_text): |
| 95 | + return ( |
| 96 | + "Extract the following details from the clinical trial brief summary in markdown format with clear section headings (e.g., ## Study Design, ## Population, etc.):\n" |
| 97 | + "- Study design\n" |
| 98 | + "- Population\n" |
| 99 | + "- Interventions\n" |
| 100 | + "- Primary and secondary endpoints\n" |
| 101 | + "- Study duration\n\n" |
| 102 | + f"Brief summary text:\n{brief_text}" |
| 103 | + ) |
| 104 | + system_prompt = "You are a clinical research assistant. Extract and list the requested protocol details in markdown format with clear section headings." |
| 105 | + messages = [ |
| 106 | + {"role": "system", "content": system_prompt}, |
| 107 | + {"role": "user", "content": user_prompt_for_protocol_brief(brief)} |
| 108 | + ] |
| 109 | + with st.spinner("Summarizing with LLM..."): |
| 110 | + try: |
| 111 | + response = openai.chat.completions.create( |
| 112 | + model="gpt-4o-mini", |
| 113 | + messages=messages |
| 114 | + ) |
| 115 | + summary = response.choices[0].message.content |
| 116 | + st.markdown(summary) |
| 117 | + except Exception as e: |
| 118 | + st.error(f"LLM call failed: {e}") |
| 119 | +else: |
| 120 | + if query: |
| 121 | + st.info("No results found. Try a different keyword.") |
0 commit comments