Spaces:
Build error
Build error
UPDATED APP Directly in HF files
Browse files
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
-
from transformers import BertTokenizer, BertForSequenceClassification
|
| 4 |
import openai
|
| 5 |
import os
|
| 6 |
import faiss
|
|
@@ -8,13 +8,11 @@ import numpy as np
|
|
| 8 |
import requests
|
| 9 |
from datasets import load_dataset
|
| 10 |
|
| 11 |
-
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
# Load
|
| 14 |
-
openai.api_key = os.getenv("OPENAI_API_KEY") # Ensure the OpenAI API key is pulled correctly
|
| 15 |
-
serper_api_key = os.getenv("SERPER_API_KEY") # Ensure the Serper API key is pulled correctly
|
| 16 |
-
|
| 17 |
-
# Load PubMedBERT tokenizer and model for FDA-related processing
|
| 18 |
tokenizer = BertTokenizer.from_pretrained("microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract")
|
| 19 |
model = BertForSequenceClassification.from_pretrained("microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract", num_labels=2)
|
| 20 |
|
|
@@ -22,24 +20,25 @@ model = BertForSequenceClassification.from_pretrained("microsoft/BiomedNLP-PubMe
|
|
| 22 |
dimension = 768 # PubMedBERT embedding size
|
| 23 |
index = faiss.IndexFlatL2(dimension)
|
| 24 |
|
|
|
|
| 25 |
def embed_text(text):
|
| 26 |
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding="max_length", max_length=512)
|
| 27 |
-
outputs = model(**inputs, output_hidden_states=True)
|
| 28 |
-
hidden_state = outputs.hidden_states[-1]
|
| 29 |
-
return hidden_state.mean(dim=1).detach().numpy()
|
| 30 |
|
| 31 |
-
#
|
| 32 |
past_conversation = "FDA approval for companion diagnostics requires careful documentation."
|
| 33 |
past_embedding = embed_text(past_conversation)
|
| 34 |
-
index.add(past_embedding)
|
| 35 |
|
| 36 |
-
#
|
| 37 |
def search_memory(query):
|
| 38 |
query_embedding = embed_text(query)
|
| 39 |
-
D, I = index.search(query_embedding, k=1)
|
| 40 |
return I
|
| 41 |
|
| 42 |
-
#
|
| 43 |
def handle_fda_query(query):
|
| 44 |
inputs = tokenizer(query, return_tensors="pt", padding="max_length", truncation=True)
|
| 45 |
outputs = model(**inputs)
|
|
@@ -47,20 +46,23 @@ def handle_fda_query(query):
|
|
| 47 |
response = "Processed FDA-related query via PubMedBERT"
|
| 48 |
return response
|
| 49 |
|
| 50 |
-
#
|
| 51 |
def handle_openai_query(prompt):
|
| 52 |
-
response = openai.
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
| 55 |
max_tokens=100
|
| 56 |
)
|
| 57 |
-
return response.choices[0].
|
| 58 |
|
| 59 |
# Web search with Serper API
|
| 60 |
def web_search(query):
|
| 61 |
url = f"https://google.serper.dev/search"
|
| 62 |
headers = {
|
| 63 |
-
"X-API-KEY":
|
| 64 |
}
|
| 65 |
params = {
|
| 66 |
"q": query
|
|
@@ -68,7 +70,45 @@ def web_search(query):
|
|
| 68 |
response = requests.get(url, headers=headers, params=params)
|
| 69 |
return response.json()
|
| 70 |
|
| 71 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
def respond(
|
| 73 |
message,
|
| 74 |
history: list[tuple[str, str]],
|
|
@@ -77,7 +117,7 @@ def respond(
|
|
| 77 |
temperature,
|
| 78 |
top_p,
|
| 79 |
):
|
| 80 |
-
# Prepare
|
| 81 |
messages = [{"role": "system", "content": system_message}]
|
| 82 |
|
| 83 |
for val in history:
|
|
@@ -88,35 +128,32 @@ def respond(
|
|
| 88 |
|
| 89 |
messages.append({"role": "user", "content": message})
|
| 90 |
|
| 91 |
-
# Check if
|
| 92 |
openai_response = handle_openai_query(f"Is this query FDA-related: {message}")
|
| 93 |
|
| 94 |
if "FDA" in openai_response or "regulatory" in openai_response:
|
| 95 |
# Search past conversations/memory using FAISS
|
| 96 |
memory_index = search_memory(message)
|
| 97 |
if memory_index:
|
| 98 |
-
return f"Found relevant past memory: {past_conversation}"
|
| 99 |
|
| 100 |
# If no memory match, proceed with PubMedBERT
|
| 101 |
return handle_fda_query(message)
|
| 102 |
|
| 103 |
-
# If query asks for
|
| 104 |
if "search the web" in message.lower():
|
| 105 |
return web_search(message)
|
| 106 |
|
| 107 |
-
#
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
temperature=temperature,
|
| 114 |
-
top_p=top_p,
|
| 115 |
-
):
|
| 116 |
-
token = message.choices[0].delta.content
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
|
|
|
| 120 |
|
| 121 |
|
| 122 |
# Create Gradio ChatInterface for interaction
|
|
@@ -130,5 +167,6 @@ demo = gr.ChatInterface(
|
|
| 130 |
],
|
| 131 |
)
|
| 132 |
|
|
|
|
| 133 |
if __name__ == "__main__":
|
| 134 |
demo.launch(share=True)
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
+
from transformers import BertTokenizer, BertForSequenceClassification
|
| 4 |
import openai
|
| 5 |
import os
|
| 6 |
import faiss
|
|
|
|
| 8 |
import requests
|
| 9 |
from datasets import load_dataset
|
| 10 |
|
| 11 |
+
# Load OpenAI API key and organization ID from environment variables
|
| 12 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 13 |
+
openai.Organization = os.getenv("OPENAI_ORG_ID")
|
| 14 |
|
| 15 |
+
# Load PubMedBERT tokenizer and model
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
tokenizer = BertTokenizer.from_pretrained("microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract")
|
| 17 |
model = BertForSequenceClassification.from_pretrained("microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract", num_labels=2)
|
| 18 |
|
|
|
|
| 20 |
dimension = 768 # PubMedBERT embedding size
|
| 21 |
index = faiss.IndexFlatL2(dimension)
|
| 22 |
|
| 23 |
+
# Embed text using PubMedBERT
|
| 24 |
def embed_text(text):
|
| 25 |
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding="max_length", max_length=512)
|
| 26 |
+
outputs = model(**inputs, output_hidden_states=True)
|
| 27 |
+
hidden_state = outputs.hidden_states[-1]
|
| 28 |
+
return hidden_state.mean(dim=1).detach().numpy()
|
| 29 |
|
| 30 |
+
# Add past conversation embedding to FAISS index
|
| 31 |
past_conversation = "FDA approval for companion diagnostics requires careful documentation."
|
| 32 |
past_embedding = embed_text(past_conversation)
|
| 33 |
+
index.add([past_embedding])
|
| 34 |
|
| 35 |
+
# Search past conversations/memory using FAISS
|
| 36 |
def search_memory(query):
|
| 37 |
query_embedding = embed_text(query)
|
| 38 |
+
D, I = index.search(query_embedding, k=1)
|
| 39 |
return I
|
| 40 |
|
| 41 |
+
# Handle FDA-specific queries with PubMedBERT
|
| 42 |
def handle_fda_query(query):
|
| 43 |
inputs = tokenizer(query, return_tensors="pt", padding="max_length", truncation=True)
|
| 44 |
outputs = model(**inputs)
|
|
|
|
| 46 |
response = "Processed FDA-related query via PubMedBERT"
|
| 47 |
return response
|
| 48 |
|
| 49 |
+
# Handle general queries using GPT-4O
|
| 50 |
def handle_openai_query(prompt):
|
| 51 |
+
response = openai.Chat.create(
|
| 52 |
+
model="gpt-4-0314-16k-512",
|
| 53 |
+
messages=[
|
| 54 |
+
{"role": "user", "content": prompt}
|
| 55 |
+
],
|
| 56 |
+
temperature=0.7,
|
| 57 |
max_tokens=100
|
| 58 |
)
|
| 59 |
+
return response.choices[0].message.content
|
| 60 |
|
| 61 |
# Web search with Serper API
|
| 62 |
def web_search(query):
|
| 63 |
url = f"https://google.serper.dev/search"
|
| 64 |
headers = {
|
| 65 |
+
"X-API-KEY": os.getenv("SERPER_API_KEY")
|
| 66 |
}
|
| 67 |
params = {
|
| 68 |
"q": query
|
|
|
|
| 70 |
response = requests.get(url, headers=headers, params=params)
|
| 71 |
return response.json()
|
| 72 |
|
| 73 |
+
# Contextual Short-Term Memory (CSTM)
|
| 74 |
+
cstm = []
|
| 75 |
+
|
| 76 |
+
# Long-Term Memory (LTM)
|
| 77 |
+
ltm = [] # Load knowledge base articles or FAQs
|
| 78 |
+
|
| 79 |
+
# Semantic search function
|
| 80 |
+
def semantic_search(query, cstm, ltm):
|
| 81 |
+
# Generate embeddings for query and CSTM/LTM
|
| 82 |
+
query_embedding = embed_text(query)
|
| 83 |
+
cstm_embeddings = [embed_text(text) for text in cstm]
|
| 84 |
+
ltm_embeddings = [embed_text(text) for text in ltm]
|
| 85 |
+
|
| 86 |
+
# Calculate similarity scores
|
| 87 |
+
cstm_scores = calculate_similarity(query_embedding, cstm_embeddings)
|
| 88 |
+
ltm_scores = calculate_similarity(query_embedding, ltm_embeddings)
|
| 89 |
+
|
| 90 |
+
# Retrieve top relevant results from CSTM and LTM
|
| 91 |
+
top_cstm = np.argmax(cstm_scores)
|
| 92 |
+
top_ltm = np.argmax(ltm_scores)
|
| 93 |
+
|
| 94 |
+
return top_cstm, top_ltm
|
| 95 |
+
|
| 96 |
+
# Calculate similarity between embeddings
|
| 97 |
+
def calculate_similarity(query_embedding, embeddings):
|
| 98 |
+
similarity_scores = []
|
| 99 |
+
for embedding in embeddings:
|
| 100 |
+
score = cosine_similarity(query_embedding, embedding)
|
| 101 |
+
similarity_scores.append(score)
|
| 102 |
+
return similarity_scores
|
| 103 |
+
|
| 104 |
+
# Cosine similarity function
|
| 105 |
+
def cosine_similarity(a, b):
|
| 106 |
+
dot_product = np.dot(a, b)
|
| 107 |
+
magnitude_a = np.linalg.norm(a)
|
| 108 |
+
magnitude_b = np.linalg.norm(b)
|
| 109 |
+
return dot_product / (magnitude_a * magnitude_b)
|
| 110 |
+
|
| 111 |
+
# Main assistant function
|
| 112 |
def respond(
|
| 113 |
message,
|
| 114 |
history: list[tuple[str, str]],
|
|
|
|
| 117 |
temperature,
|
| 118 |
top_p,
|
| 119 |
):
|
| 120 |
+
# Prepare context for OpenAI and PubMedBERT
|
| 121 |
messages = [{"role": "system", "content": system_message}]
|
| 122 |
|
| 123 |
for val in history:
|
|
|
|
| 128 |
|
| 129 |
messages.append({"role": "user", "content": message})
|
| 130 |
|
| 131 |
+
# Check if query is FDA-related
|
| 132 |
openai_response = handle_openai_query(f"Is this query FDA-related: {message}")
|
| 133 |
|
| 134 |
if "FDA" in openai_response or "regulatory" in openai_response:
|
| 135 |
# Search past conversations/memory using FAISS
|
| 136 |
memory_index = search_memory(message)
|
| 137 |
if memory_index:
|
| 138 |
+
return f"Found relevant past memory: {past_conversation}"
|
| 139 |
|
| 140 |
# If no memory match, proceed with PubMedBERT
|
| 141 |
return handle_fda_query(message)
|
| 142 |
|
| 143 |
+
# If query asks for web search, perform web search
|
| 144 |
if "search the web" in message.lower():
|
| 145 |
return web_search(message)
|
| 146 |
|
| 147 |
+
# Perform semantic search on CSTM and LTM
|
| 148 |
+
top_cstm, top_ltm = semantic_search(message, cstm, ltm)
|
| 149 |
+
if top_cstm:
|
| 150 |
+
return f"Found relevant context: {cstm[top_cstm]}"
|
| 151 |
+
elif top_ltm:
|
| 152 |
+
return f"Found relevant knowledge: {ltm[top_ltm]}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
+
# General conversational handling with GPT-4O
|
| 155 |
+
response = handle_openai_query(message)
|
| 156 |
+
return response
|
| 157 |
|
| 158 |
|
| 159 |
# Create Gradio ChatInterface for interaction
|
|
|
|
| 167 |
],
|
| 168 |
)
|
| 169 |
|
| 170 |
+
|
| 171 |
if __name__ == "__main__":
|
| 172 |
demo.launch(share=True)
|