kenton-li commited on
Commit
dd05464
·
1 Parent(s): 35b6e6d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +163 -0
app.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import time
4
+ import openai
5
+ import pandas as pd
6
+
7
+ openai_api_key_textbox = ""
8
+ model = None
9
+ tokenizer = None
10
+ generator = None
11
+ csv_name = "disease_database_mini.csv"
12
+ df = pd.read_csv(csv_name)
13
+ openai.api_key = "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"
14
+
15
+ def csv_prompter(question,csv_name):
16
+
17
+
18
+
19
+ fulltext = "A question is provided below. Given the question, extract " + \
20
+ "keywords from the text. Focus on extracting the keywords that we can use " + \
21
+ "to best lookup answers to the question. \n" + \
22
+ "---------------------\n" + \
23
+ "{}\n".format(question) + \
24
+ "---------------------\n" + \
25
+ "Provide keywords in the following comma-separated format.\nKeywords: "
26
+
27
+ messages = [
28
+ {"role": "system", "content": ""},
29
+ ]
30
+ messages.append(
31
+ {"role": "user", "content": f"{fulltext}"}
32
+ )
33
+ rsp = openai.ChatCompletion.create(
34
+ model="gpt-3.5-turbo",
35
+ messages=messages
36
+ )
37
+ keyword_list = rsp.get("choices")[0]["message"]["content"]
38
+ keyword_list = keyword_list.replace(",","").split(" ")
39
+
40
+ print(keyword_list)
41
+ divided_text = []
42
+ csvdata = df.to_dict('records')
43
+ step_length = 15
44
+ for csv_item in range(0,len(csvdata),step_length):
45
+ csv_text = str(csvdata[csv_item:csv_item+step_length]).replace("}, {", "\n\n").replace("\"", "")#.replace("[", "").replace("]", "")
46
+ divided_text.append(csv_text)
47
+
48
+ answer_llm = ""
49
+
50
+ score_textlist = [0] * len(divided_text)
51
+
52
+ for i, chunk in enumerate(divided_text):
53
+ for t, keyw in enumerate(keyword_list):
54
+ if keyw.lower() in chunk.lower():
55
+ score_textlist[i] = score_textlist[i] + 1
56
+
57
+ answer_list = []
58
+ divided_text = [item for _, item in sorted(zip(score_textlist, divided_text), reverse=True)]
59
+
60
+ for i, chunk in enumerate(divided_text):
61
+
62
+ if i>4:
63
+ continue
64
+
65
+ fulltext = "{}".format(chunk) + \
66
+ "\n---------------------\n" + \
67
+ "Based on the Table above and not prior knowledge, " + \
68
+ "Select the Table Entries that will help to answer the question: {}\n Output in the format of \" Disease: <>; Symptom: <>; Medical Test: <>; Medications: <>;\". If there is no useful form entries, output: 'No Entry'".format(question)
69
+
70
+ print(fulltext)
71
+ messages = [
72
+ {"role": "system", "content": ""},
73
+ ]
74
+ messages.append(
75
+ {"role": "user", "content": f"{fulltext}"}
76
+ )
77
+ rsp = openai.ChatCompletion.create(
78
+ model="gpt-3.5-turbo",
79
+ messages=messages
80
+ )
81
+ answer_llm = rsp.get("choices")[0]["message"]["content"]
82
+
83
+ print("\nAnswer: " + answer_llm)
84
+ print()
85
+ if not "No Entry" in answer_llm:
86
+ answer_list.append(answer_llm)
87
+
88
+
89
+
90
+ fulltext = "The original question is as follows: {}\n".format(question) + \
91
+ "Based on this Table:\n" + \
92
+ "------------\n" + \
93
+ "{}\n".format(str("\n\n".join(answer_list))) + \
94
+ "------------\n" + \
95
+ "Answer: "
96
+ print(fulltext)
97
+ messages = [
98
+ {"role": "system", "content": ""},
99
+ ]
100
+ messages.append(
101
+ {"role": "user", "content": f"{fulltext}"}
102
+ )
103
+ rsp = openai.ChatCompletion.create(
104
+ model="gpt-3.5-turbo",
105
+ messages=messages
106
+ )
107
+ answer_llm = rsp.get("choices")[0]["message"]["content"]
108
+
109
+ print("\nFinal Answer: " + answer_llm)
110
+ print()
111
+
112
+ return answer_llm
113
+
114
+
115
+
116
+ with gr.Blocks() as demo:
117
+ gr.Markdown("# Autonomous ChatDoctor (openai version), based on disease database knowledge")
118
+ gr.Markdown("## Example: If I have frontal headache, fever, and painful sinuses, what disease should I have, and what medical test should I take?")
119
+ gr.Markdown("Our model will answer based on the content of the excel below, so please try to ask questions based on the table content.")
120
+
121
+ chatbot = gr.Chatbot()
122
+ msg = gr.Textbox()
123
+ clear = gr.Button("Clear")
124
+ Initialization = gr.Button("Initialization")
125
+
126
+ def restart(history):
127
+ invitation = "ChatDoctor: "
128
+ human_invitation = "Patient: "
129
+ return [[" \n",invitation+" I am ChatDoctor, what medical questions do you have?"]]
130
+
131
+ def user(user_message, history):
132
+ invitation = "ChatDoctor: "
133
+ human_invitation = "Patient: "
134
+ return "", history +[[human_invitation+user_message, None]]
135
+
136
+ def bot(history):
137
+ invitation = "ChatDoctor: "
138
+ human_invitation = "Patient: "
139
+ print(history)
140
+
141
+
142
+ question = ""
143
+ for each_ques in history:
144
+ question = question+ each_ques[0].replace("Patient: ","")+" \n"
145
+
146
+ response = csv_prompter(question,csv_name)
147
+
148
+ response = invitation+ response
149
+ history[-1][1] = response
150
+
151
+ return history
152
+
153
+ msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
154
+ bot, chatbot, chatbot
155
+ )
156
+ clear.click(lambda: None, None, chatbot, queue=False).then(restart, chatbot, chatbot)
157
+ Initialization.click(lambda: None, None, chatbot, queue=False).then(restart, chatbot, chatbot)
158
+
159
+
160
+
161
+ if __name__ == "__main__":
162
+ demo.launch()
163
+