File size: 5,429 Bytes
c84c42d
 
 
 
 
 
4ff927f
c84c42d
 
4ff927f
c84c42d
 
 
 
245bf90
 
c84c42d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2ecf15
c84c42d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b605abd
c84c42d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63b35e0
 
2b7a8c1
 
4581fe2
c84c42d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df0437c
4ff927f
 
df0437c
fbcd12e
c35762b
b613472
fbcd12e
d8f7197
c84c42d
 
 
 
 
 
 
 
 
 
 
9c612d1
c84c42d
6dbbd5e
c84c42d
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import gradio as gr
import os
import time
import openai
import pandas as pd

openai.api_key = ""


openai_api_key_textbox = ""
model = None
tokenizer = None
generator = None
csv_name = "disease_database_mini.csv"
df = pd.read_csv(csv_name)


def csv_prompter(question,csv_name):


    fulltext = "A question is provided below. Given the question, extract " + \
               "keywords from the text. Focus on extracting the keywords that we can use " + \
               "to best lookup answers to the question. \n" + \
               "---------------------\n" + \
               "{}\n".format(question) + \
               "---------------------\n" + \
               "Provide keywords in the following comma-separated format.\nKeywords: "

    messages = [
        {"role": "system", "content": ""},
    ]
    messages.append(
        {"role": "user", "content": f"{fulltext}"}
    )
    rsp = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=messages
    )
    keyword_list = rsp.get("choices")[0]["message"]["content"]
    keyword_list = keyword_list.replace(",","").split(" ")

    print(keyword_list)
    divided_text = []
    csvdata = df.to_dict('records')
    step_length = 15
    for csv_item in range(0,len(csvdata),step_length):
        csv_text = str(csvdata[csv_item:csv_item+step_length]).replace("}, {", "\n\n").replace("\"", "")#.replace("[", "").replace("]", "")
        divided_text.append(csv_text)

    answer_llm = ""

    score_textlist = [0] * len(divided_text)

    for i, chunk in enumerate(divided_text):
        for t, keyw in enumerate(keyword_list):
            if keyw.lower() in chunk.lower():
                score_textlist[i] = score_textlist[i] + 1

    answer_list = []
    divided_text = [item for _, item in sorted(zip(score_textlist, divided_text), reverse=True)]

    for i, chunk in enumerate(divided_text):

        if i>4:
            continue

        fulltext = "{}".format(chunk) + \
                   "\n---------------------\n" + \
                   "Based on the Table above and not prior knowledge, " + \
                   "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)

        print(fulltext)
        messages = [
            {"role": "system", "content": ""},
        ]
        messages.append(
            {"role": "user", "content": f"{fulltext}"}
        )
        rsp = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=messages
        )
        answer_llm = rsp.get("choices")[0]["message"]["content"]

        print("\nAnswer: " + answer_llm)
        print()
        if not "No Entry" in answer_llm:
            answer_list.append(answer_llm)



    fulltext = "The original question is as follows: {}\n".format(question) + \
               "Based on this Table:\n" + \
               "------------\n" + \
               "{}\n".format(str("\n\n".join(answer_list))) + \
               "------------\n" + \
               "Answer: "
    print(fulltext)
    messages = [
        {"role": "system", "content": ""},
    ]
    messages.append(
        {"role": "user", "content": f"{fulltext}"}
    )
    rsp = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=messages
    )
    answer_llm = rsp.get("choices")[0]["message"]["content"]

    print("\nFinal Answer: " + answer_llm)
    print()

    return answer_llm



with gr.Blocks() as demo:
    gr.Markdown("# Autonomous ChatDoctor (openai version), based on disease database knowledge")
    gr.Markdown("## Example: If I have frontal headache, fever, and painful sinuses, what disease should I have, and what medical test should I take?")
    openai_api_key_textbox = gr.Textbox(placeholder="Paste your OpenAI API key (sk-...) and hit Enter",
                                                show_label=False, lines=1, type='password')
    
    chatbot = gr.Chatbot()
    msg = gr.Textbox()
    clear = gr.Button("Clear")
    Initialization = gr.Button("Initialization")

    def restart(history):
        invitation = "ChatDoctor: "
        human_invitation = "Patient: "
        return [[None,invitation+" I am ChatDoctor, what medical questions do you have?"]]
            
    def user(user_message, history):
        invitation = "ChatDoctor: "
        human_invitation = "Patient: "
        return "", history +[[human_invitation+user_message, None]]

    def bot(history):
        invitation = "ChatDoctor: "
        human_invitation = "Patient: "
        print(history)
        print(openai_api_key_textbox)
        openai.api_key = openai_api_key_textbox
        
        question = ""
        for each_ques in history:
            question = question+ each_ques[0].replace("Patient: ","")+" \n"

        response = csv_prompter(question,csv_name)
        
        response = invitation+ response
        history[-1][1] = response

        return history

    msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
        bot, chatbot, chatbot
    )
    clear.click(lambda: None, None, chatbot, queue=False).then(restart, chatbot, chatbot)
    Initialization.click(lambda: None, None, chatbot, queue=False).then(restart, chatbot, chatbot)
    gr.Dataframe(df)

    
if __name__ == "__main__":
    demo.launch()