cloud-sean commited on
Commit
852ef53
·
1 Parent(s): e82f7ba

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -0
app.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import streamlit as st
3
+ import os
4
+ import json
5
+ import time
6
+ from annotated_text import annotated_text
7
+
8
+
9
+ with open('demo.json') as f:
10
+ tmp = json.load(f)
11
+
12
+
13
+ dax_input = st.text_area("DAX input")
14
+
15
+
16
+ def generate_annotated_array(text, json_data):
17
+ """
18
+ Generate an array of strings based on annotations from the JSON data.
19
+
20
+ Parameters:
21
+ - text (str): The input text to be annotated.
22
+ - json_data (dict): The JSON data containing annotations.
23
+
24
+ Returns:
25
+ - list: An array of strings with separate elements for each annotation.
26
+ """
27
+ entities = json_data['documents'][0]['entities']
28
+ output = []
29
+ index = 0
30
+ buffer_text = ""
31
+
32
+ while index < len(text):
33
+ # Find the entity that matches the current position
34
+ entity = next((e for e in entities if e['offset'] == index), None)
35
+
36
+ if entity:
37
+ # If there's buffer_text, add it to the output
38
+ if buffer_text:
39
+ output.append(buffer_text)
40
+ buffer_text = ""
41
+
42
+ # Add the annotated entity to the output
43
+ output.append("[" + entity['text'] + ":" + entity['category'] + "]")
44
+ index += entity['length']
45
+ else:
46
+ # If no entity is found, add the character to buffer_text
47
+ buffer_text += text[index]
48
+ index += 1
49
+
50
+ # Add any remaining buffer_text to the output
51
+ if buffer_text:
52
+ output.append(buffer_text)
53
+
54
+ return output
55
+
56
+ import requests
57
+
58
+
59
+ import requests
60
+ import time
61
+
62
+ def analyze_healthcare_text(text):
63
+ # Endpoint, headers and subscription key
64
+ base_url = "https://ta4h-endpoint.cognitiveservices.azure.com/language/analyze-text/jobs"
65
+ headers = {
66
+ "Content-Type": "application/json",
67
+ "Ocp-Apim-Subscription-Key": "00667ce9381d46a3a279c4799dd698d0"
68
+ }
69
+
70
+ # Data to be sent in the initial POST request
71
+ data = {
72
+ "tasks": [{"kind": "Healthcare"}],
73
+ "analysisInput": {
74
+ "documents": [
75
+ {
76
+ "id": "documentId",
77
+ "text": text,
78
+ "language": "en"
79
+ }
80
+ ]
81
+ }
82
+ }
83
+
84
+ # Making the initial POST request
85
+ response = requests.post(f"{base_url}?api-version=2022-10-01-preview", headers=headers, json=data)
86
+
87
+ time.sleep(10)
88
+
89
+ # Get the operation-location from the response header
90
+ operation_location = response.headers.get('operation-location')
91
+
92
+ # Extract JOB-ID from the operation-location
93
+ job_id = operation_location.split('/')[-1].split('?')[0]
94
+
95
+ # Make a subsequent GET request to retrieve the results using the JOB-ID
96
+ result_response = requests.get(f"{base_url}/{job_id}?api-version=2022-10-01-preview", headers=headers)
97
+
98
+ # Return the JSON response from the GET request
99
+ result = result_response.json()
100
+
101
+ return result
102
+
103
+
104
+
105
+ def convert_to_annotated_text(input_list):
106
+ """
107
+ Convert a list with annotated content into a nested list suitable for annotated_text format.
108
+
109
+ Args:
110
+ - input_list (list): The list with content and annotations in format '[text:annotation]'.
111
+
112
+ Returns:
113
+ - list: A nested list in the annotated_text format.
114
+ """
115
+ annotated_list = []
116
+ temp_group = []
117
+
118
+ for item in input_list:
119
+ # Check if the item is an annotation
120
+ if item.startswith('[') and item.endswith(']'):
121
+ content = item[1:-1].split(':')
122
+ temp_group.append((content[0], content[1]))
123
+ else:
124
+ if temp_group: # if there are items in the temporary group
125
+ annotated_list.append(temp_group)
126
+ temp_group = []
127
+ annotated_list.append(item)
128
+
129
+ # Add any remaining items in the temporary group to the final list
130
+ if temp_group:
131
+ annotated_list.append(temp_group)
132
+
133
+ return annotated_list
134
+
135
+
136
+ if st.button("Analyze"):
137
+ text = dax_input
138
+ json_analysis = analyze_healthcare_text(text)
139
+ json_analysis = json_analysis["tasks"]["items"][0]["results"]
140
+ # save json analysis as a file
141
+
142
+
143
+ new_text = generate_annotated_array(text, json_analysis)
144
+ new_text = convert_to_annotated_text(new_text)
145
+ annotated_text(new_text)
146
+
147
+
148
+
149
+
150
+ st.title("Nuance DAX Copilot")
151
+
152
+ os.environ["OPENAI_API_BASE"] = openai.api_type = "azure"
153
+ os.environ["OPENAI_API_BASE"] = openai.api_base = "https://eastus-openai-sean.openai.azure.com/"
154
+ os.environ["OPENAI_API_VERSION"] = openai.api_version = "2023-03-15-preview"
155
+
156
+ openai.api_key = os.environ["OPENAI_API_KEY"]
157
+ openai.api_version = os.environ["OPENAI_API_VERSION"]
158
+ openai.api_base = os.environ["OPENAI_API_BASE"]
159
+ os.environ["OPENAI_API_VERSION"] = openai.api_version = "2023-03-15-preview"
160
+
161
+
162
+ if "messages" not in st.session_state:
163
+ st.session_state.messages = [{"role":"system","content":"You are an AI assistant that ansswers questions about patient encounters. You are not a doctor and should not diagnose or treat patients. However, you can suggest common practices and help doctors with their questions that will help them make better decisions. \ Use only the information below: \n Patient Note / Encounter Summary: \n"}]
164
+
165
+
166
+ for message in st.session_state.messages:
167
+ with st.chat_message(message["role"]):
168
+ st.markdown(message["content"])
169
+
170
+
171
+
172
+
173
+
174
+
175
+ if prompt := st.chat_input("Nuance DAX Copilot?"):
176
+ st.session_state.messages.append({"role": "user", "content": prompt + dax_input})
177
+ with st.chat_message("user"):
178
+ st.markdown(prompt)
179
+
180
+ with st.chat_message("assistant"):
181
+ message_placeholder = st.empty()
182
+ full_response = ""
183
+ for response in openai.ChatCompletion.create(
184
+ messages=[
185
+ {"role": m["role"], "content": m["content"]}
186
+ for m in st.session_state.messages
187
+ ],
188
+ stream=True,
189
+ engine="gpt-4",
190
+ ):
191
+ full_response += response.choices[0].delta.get("content", "")
192
+ message_placeholder.markdown(full_response + "▌")
193
+ message_placeholder.markdown(full_response)
194
+ st.session_state.messages.append({"role": "assistant", "content": full_response})