eudoxie commited on
Commit
26b1c4d
·
verified ·
1 Parent(s): 6064038

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -48
app.py CHANGED
@@ -1,64 +1,138 @@
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
  """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
 
60
  )
61
 
62
 
63
  if __name__ == "__main__":
64
  demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
 
2
 
3
+ df = pd.read_csv("./drugs_side_effects_drugs_com.csv")
4
+ df.info()
 
 
5
 
6
+ df = df[['drug_name', 'medical_condition', 'side_effects']]
7
+ df.dropna(inplace=True)
8
 
9
+ df.info()
 
 
 
 
 
 
 
 
10
 
11
+ context_data = pd.read_csv("drugs_side_effects_drugs_com.csv")
 
 
 
 
12
 
13
+ import os
14
+ from google.colab import userdata
15
+ groq_api_key = userdata.get('Groq_API_key')
16
 
17
+ from langchain_groq import ChatGroq
18
 
19
+ llm = ChatGroq(model="llama-3.1-70b-versatile",api_key=groq_api_key)
 
 
 
 
 
 
 
20
 
21
+ ## Embedding model!
22
+ from langchain_huggingface import HuggingFaceEmbeddings
23
+ embed_model = HuggingFaceEmbeddings(model_name="mixedbread-ai/mxbai-embed-large-v1")
24
 
25
+ # create vector store!
26
+ from langchain_chroma import Chroma
27
+
28
+ vectorstore = Chroma(
29
+ collection_name="medical_dataset_store",
30
+ embedding_function=embed_model,
31
+ persist_directory="./",
32
+ )
33
+
34
+ vectorstore.get().keys()
35
+
36
+ # add data to vector nstore
37
+ vectorstore.add_texts(context_data)
38
+
39
+ query = "What drug that causes these side effects hives ; difficulty breathing; swelling of your face, lips, tongue, or throat."
40
+ docs = vectorstore.similarity_search(query)
41
+ print(docs[0].page_content)
42
+
43
+ retriever = vectorstore.as_retriever()
44
+
45
+ from langchain_core.prompts import PromptTemplate
46
+
47
+ template = ("""You are a medical expert.
48
+ Use the provided context to answer the question.
49
+ If you don't know the answer, say so. Explain your answer in detail.
50
+ Do not discuss the context in your response; just provide the answer directly.
51
+
52
+ Context: {context}
53
+
54
+ Question: {question}
55
+
56
+ Answer:""")
57
+
58
+ rag_prompt = PromptTemplate.from_template(template)
59
+
60
+ from langchain_core.output_parsers import StrOutputParser
61
+ from langchain_core.runnables import RunnablePassthrough
62
+
63
+ rag_chain = (
64
+ {"context": retriever, "question": RunnablePassthrough()}
65
+ | rag_prompt
66
+ | llm
67
+ | StrOutputParser()
68
+ )
69
+
70
+ from IPython.display import display, Markdown
71
+
72
+ response = rag_chain.invoke("What drug that causes these side effects hives ; difficulty breathing; swelling of your face, lips, tongue, or throat")
73
+ Markdown(response)
74
+
75
+ from IPython.display import display, Markdown
76
+
77
+ response = rag_chain.invoke("What is Capital of Greece?")
78
+ Markdown(response)
79
+
80
+ """# Deployment
81
 
82
  """
83
+
84
+ import gradio as gr
85
+
86
+ def rag_memory_stream(text):
87
+ partial_text = ""
88
+ for new_text in rag_chain.stream(text):
89
+ partial_text += new_text
90
+ yield partial_text
91
+
92
+
93
+ title = "MediGuide ChatBot"
94
+ demo = gr.Interface(
95
+ title=title,
96
+ fn=rag_memory_stream,
97
+ inputs="text",
98
+ outputs="text",
99
+ allow_flagging="never",
100
  )
101
 
102
 
103
  if __name__ == "__main__":
104
  demo.launch()
105
+
106
+ """# Evaluating Using Blue Score and Rouge Score"""
107
+
108
+ # qa_pair = []
109
+ # for i in range(len(context_data)):
110
+ # drug_name = str(context_data['drug_name'][i])
111
+ # medical_condition = str(context_data['medical_condition'][i])
112
+ # side_effects = str(context_data['side_effects'][i])
113
+
114
+ # Question = f"What are the side effect of {drug_name} ?"
115
+ # Answer = f"Side Effects: {side_effects}"
116
+
117
+ # qa_pair.append([Question,Answer])
118
+
119
+ # df = pd.DataFrame(qa_pair, columns=['Questions', 'Answers'])
120
+
121
+ # question = [df['Questions'][0]]
122
+
123
+ # import sacrebleu
124
+ # from rouge_score import rouge_scorer
125
+
126
+ # predicted_answer = rag_chain.invoke("What are the side effects of doxycycline?")
127
+ # predicted_answer
128
+
129
+ # reference_answer =df['Answers'][0]
130
+ # reference_answer
131
+
132
+ # blue_score = sacrebleu.corpus_bleu([predicted_answer], reference_answer).score
133
+ # blue_score
134
+
135
+ # scorer = rouge_scorer.RougeScorer(['rougeL'], use_stemmer=True)
136
+ # rouge_score = scorer.score(reference_answer, predicted_answer)
137
+ # rouge_score
138
+