pretzinger commited on
Commit
cd77e73
·
verified ·
1 Parent(s): 5279001

Updated app.py w new code

Browse files
Files changed (1) hide show
  1. app.py +82 -63
app.py CHANGED
@@ -1,63 +1,82 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
-
61
-
62
- if __name__ == "__main__":
63
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset
2
+ from transformers import BertTokenizer, BertForSequenceClassification, TrainingArguments, Trainer
3
+ import openai
4
+ import faiss
5
+ import numpy as np
6
+
7
+ # Set up OpenAI API key for GPT-4
8
+ openai.api_key = "your_openai_api_key"
9
+
10
+ # Load PubMedBERT tokenizer and model
11
+ tokenizer = BertTokenizer.from_pretrained("microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract")
12
+ model = BertForSequenceClassification.from_pretrained("microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract", num_labels=2)
13
+
14
+ # Load the FDA dataset from Hugging Face
15
+ dataset = load_dataset("pretzinger/cdx-cleared-approved", split="train")
16
+
17
+ # Tokenize the dataset
18
+ def tokenize_function(example):
19
+ return tokenizer(example["text"], padding="max_length", truncation=True)
20
+
21
+ tokenized_dataset = dataset.map(tokenize_function, batched=True)
22
+
23
+ # FAISS setup for vector search (embedding-based memory)
24
+ dimension = 768 # PubMedBERT embedding size
25
+ index = faiss.IndexFlatL2(dimension)
26
+
27
+ def embed_text(text):
28
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, padding="max_length", max_length=512)
29
+ outputs = model(**inputs)
30
+ return outputs.last_hidden_state.mean(dim=1).detach().numpy()
31
+
32
+ # Example: Embed past conversation and store in FAISS
33
+ past_conversation = "FDA approval for companion diagnostics requires careful documentation."
34
+ past_embedding = embed_text(past_conversation)
35
+ index.add(past_embedding)
36
+
37
+ # Embed the incoming query and search for related memory
38
+ def search_memory(query):
39
+ query_embedding = embed_text(query)
40
+ D, I = index.search(query_embedding, k=1) # Retrieve most similar past conversation
41
+ return I
42
+
43
+ # Function to handle FDA-related queries with PubMedBERT
44
+ def handle_fda_query(query):
45
+ # If query requires specific FDA info, process it with PubMedBERT
46
+ inputs = tokenizer(query, return_tensors="pt", padding="max_length", truncation=True)
47
+ outputs = model(**inputs)
48
+ logits = outputs.logits
49
+ # Process logits for classification or output a meaningful response
50
+ response = "Processed FDA-related query via PubMedBERT"
51
+ return response
52
+
53
+ # Function to handle general queries using GPT-4
54
+ def handle_openai_query(prompt):
55
+ response = openai.Completion.create(
56
+ engine="gpt-4", # Ensuring GPT-4 usage
57
+ prompt=prompt,
58
+ max_tokens=100
59
+ )
60
+ return response.choices[0].text.strip()
61
+
62
+ # Main assistant function that delegates to either OpenAI or PubMedBERT
63
+ def assistant(query):
64
+ # First, determine if query needs FDA-specific info
65
+ openai_response = handle_openai_query(f"Is this query FDA-related: {query}")
66
+
67
+ if "FDA" in openai_response or "regulatory" in openai_response:
68
+ # Search past conversations/memory using FAISS
69
+ memory_index = search_memory(query)
70
+ if memory_index:
71
+ return f"Found relevant past memory: {past_conversation}" # Return past context from memory
72
+
73
+ # If no memory match, proceed with PubMedBERT
74
+ return handle_fda_query(query)
75
+
76
+ # General conversational handling with OpenAI (GPT-4)
77
+ return openai_response
78
+
79
+ # Example Usage
80
+ query = "What is required for PMA approval for companion diagnostics?"
81
+ response = assistant(query)
82
+ print(response)