srijaydeshpande commited on
Commit
fdfb509
·
1 Parent(s): f4a17dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +201 -153
app.py CHANGED
@@ -1,158 +1,206 @@
1
- from pdfminer.high_level import extract_pages
2
- from pdfminer.layout import LTTextContainer
3
- from tqdm import tqdm
4
- import re
5
- import gradio as gr
6
- import os
7
- import accelerate
8
- import spaces
9
- import subprocess
10
- from huggingface_hub import hf_hub_download
11
-
12
- subprocess.run('pip install llama-cpp-python==0.2.75 --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu124', shell=True)
13
- subprocess.run('pip install llama-cpp-agent==0.2.10', shell=True)
14
-
15
- from llama_cpp import Llama
16
-
17
- hf_hub_download(
18
- repo_id="QuantFactory/Meta-Llama-3-8B-Instruct-GGUF",
19
- filename="Meta-Llama-3-8B-Instruct.Q8_0.gguf",
20
- local_dir = "./models"
21
- )
22
 
23
  # hf_hub_download(
24
- # repo_id="bartowski/Llama-3-8B-Instruct-Gradient-1048k-GGUF",
25
- # filename="Llama-3-8B-Instruct-Gradient-1048k-Q8_0.gguf",
26
  # local_dir = "./models"
27
  # )
28
 
29
- def process_document(pdf_path, page_ids=None):
30
- extracted_pages = extract_pages(pdf_path, page_numbers=page_ids)
31
-
32
- page2content = {}
33
-
34
- for extracted_page in tqdm(extracted_pages):
35
- page_id = extracted_page.pageid
36
- content = process_page(extracted_page)
37
- page2content[page_id] = content
38
-
39
- return page2content
40
-
41
-
42
- def process_page(extracted_page):
43
- content = []
44
- elements = [element for element in extracted_page._objs]
45
- elements.sort(key=lambda a: a.y1, reverse=True)
46
- for i, element in enumerate(elements):
47
- if isinstance(element, LTTextContainer):
48
- line_text = extract_text_and_normalize(element)
49
- content.append(line_text)
50
- content = re.sub('\n+', ' ', ''.join(content))
51
- return content
52
-
53
-
54
- def extract_text_and_normalize(element):
55
- # Extract text from line and split it with new lines
56
- line_texts = element.get_text().split('\n')
57
- norm_text = ''
58
- for line_text in line_texts:
59
- line_text = line_text.strip()
60
- if not line_text:
61
- line_text = '\n'
62
- else:
63
- line_text = re.sub('\s+', ' ', line_text)
64
- if not re.search('[\w\d\,\-]', line_text[-1]):
65
- line_text += '\n'
66
- else:
67
- line_text += ' '
68
- norm_text += line_text
69
- return norm_text
70
-
71
-
72
- def txt_to_html(text):
73
- html_content = "<html><body>"
74
- for line in text.split('\n'):
75
- html_content += "<p>{}</p>".format(line.strip())
76
- html_content += "</body></html>"
77
- return html_content
78
-
79
-
80
- def deidentify_doc(pdftext, maxtokens, temperature, top_probability):
81
- prompt = "In the following text replace any person name and any address with term [redacted], replace any Date of Birth and NHS number with term [redacted]"
82
- # print('Prompt is ',prompt)
83
- # print('-------------------------------------------')
84
- output = model.create_chat_completion(
85
- messages=[
86
- {"role": "assistant", "content": prompt},
87
- {
88
- "role": "user",
89
- "content": pdftext
90
- }
91
- ],
92
- max_tokens=maxtokens,
93
- temperature=temperature
94
- )
95
- output = output['choices'][0]['message']['content']
96
-
97
- # print(prompt)
98
- # print(output)
99
- # print('-------------------------------------------------------')
100
-
101
- prompt = "Perform the following actions on given text: 1. Replace any person age with term [redacted] 2. DO NOT REPLACE ANY MEDICAL MEASUREMENTS 3. Replace only the CALENDAR DATES of format 'day/month/year' with term [redacted]"
102
- output = model.create_chat_completion(
103
- messages=[
104
- {"role": "assistant", "content": prompt},
105
- {
106
- "role": "user",
107
- "content": output
108
- }
109
- ],
110
- max_tokens=maxtokens,
111
- temperature=temperature
112
- )
113
- output = output['choices'][0]['message']['content']
114
-
115
- # print(prompt)
116
- # print(output)
117
- # print('-------------------------------------------------------')
118
-
119
- return output
120
-
121
- @spaces.GPU(duration=120)
122
- def pdf_to_text(files, maxtokens=2048, temperature=0, top_probability=0.95):
123
- files=[files]#remove later
124
- for file in files:
125
- file_name = os.path.basename(file)
126
- file_name_splt = file_name.split('.')
127
- # print('File name is ', file_name)
128
- if (len(file_name_splt) > 1 and file_name_splt[1] == 'pdf'):
129
- page2content = process_document(file, page_ids=[0])
130
- pdftext = page2content[1]
131
- # pdftext = file # remove later
132
- if (pdftext): #shift this if block to right later
133
- anonymized_text = deidentify_doc(pdftext, maxtokens, temperature, top_probability)
134
- return anonymized_text
135
-
136
-
137
- # model_id = "Meta-Llama-3-8B-Instruct.Q8_0.gguf"
138
- model_id = "models/Meta-Llama-3-8B-Instruct.Q8_0.gguf"
139
- model = Llama(model_path=model_id, n_ctx=2048, n_threads=8, n_gpu_layers=-1, n_batch=128)
140
-
141
- css = ".gradio-container {background: 'logo.png'}"
142
- temp_slider = gr.Slider(minimum=0, maximum=2, value=0.9, label="Temperature Value")
143
- prob_slider = gr.Slider(minimum=0, maximum=1, value=0.95, label="Max Probability Value")
144
- max_tokens = gr.Number(value=600, label="Max Tokens")
145
- input_folder = gr.File(file_count='multiple')
146
- input_folder_text = gr.Textbox(label='Enter output folder path')
147
- output_text = gr.Textbox()
148
- output_path_component = gr.File(label="Select Output Path")
149
- iface = gr.Interface(
150
- fn=pdf_to_text,
151
- inputs='file',
152
- # inputs=["textbox", input_folder_text, "textbox", max_tokens, temp_slider, prob_slider],
153
- outputs=output_text,
154
- title='COBIx Endoscopy Report De-Identification',
155
- description="This application assists to remove personal information from the uploaded clinical report",
156
- theme=gr.themes.Soft(),
157
- )
158
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # from pdfminer.high_level import extract_pages
2
+ # from pdfminer.layout import LTTextContainer
3
+ # from tqdm import tqdm
4
+ # import re
5
+ # import gradio as gr
6
+ # import os
7
+ # import accelerate
8
+ # import spaces
9
+ # import subprocess
10
+ # from huggingface_hub import hf_hub_download
11
+
12
+ # subprocess.run('pip install llama-cpp-python==0.2.75 --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu124', shell=True)
13
+ # subprocess.run('pip install llama-cpp-agent==0.2.10', shell=True)
14
+
15
+ # from llama_cpp import Llama
 
 
 
 
 
 
16
 
17
  # hf_hub_download(
18
+ # repo_id="QuantFactory/Meta-Llama-3-8B-Instruct-GGUF",
19
+ # filename="Meta-Llama-3-8B-Instruct.Q8_0.gguf",
20
  # local_dir = "./models"
21
  # )
22
 
23
+ # # hf_hub_download(
24
+ # # repo_id="bartowski/Llama-3-8B-Instruct-Gradient-1048k-GGUF",
25
+ # # filename="Llama-3-8B-Instruct-Gradient-1048k-Q8_0.gguf",
26
+ # # local_dir = "./models"
27
+ # # )
28
+
29
+ # def process_document(pdf_path, page_ids=None):
30
+ # extracted_pages = extract_pages(pdf_path, page_numbers=page_ids)
31
+
32
+ # page2content = {}
33
+
34
+ # for extracted_page in tqdm(extracted_pages):
35
+ # page_id = extracted_page.pageid
36
+ # content = process_page(extracted_page)
37
+ # page2content[page_id] = content
38
+
39
+ # return page2content
40
+
41
+
42
+ # def process_page(extracted_page):
43
+ # content = []
44
+ # elements = [element for element in extracted_page._objs]
45
+ # elements.sort(key=lambda a: a.y1, reverse=True)
46
+ # for i, element in enumerate(elements):
47
+ # if isinstance(element, LTTextContainer):
48
+ # line_text = extract_text_and_normalize(element)
49
+ # content.append(line_text)
50
+ # content = re.sub('\n+', ' ', ''.join(content))
51
+ # return content
52
+
53
+
54
+ # def extract_text_and_normalize(element):
55
+ # # Extract text from line and split it with new lines
56
+ # line_texts = element.get_text().split('\n')
57
+ # norm_text = ''
58
+ # for line_text in line_texts:
59
+ # line_text = line_text.strip()
60
+ # if not line_text:
61
+ # line_text = '\n'
62
+ # else:
63
+ # line_text = re.sub('\s+', ' ', line_text)
64
+ # if not re.search('[\w\d\,\-]', line_text[-1]):
65
+ # line_text += '\n'
66
+ # else:
67
+ # line_text += ' '
68
+ # norm_text += line_text
69
+ # return norm_text
70
+
71
+
72
+ # def txt_to_html(text):
73
+ # html_content = "<html><body>"
74
+ # for line in text.split('\n'):
75
+ # html_content += "<p>{}</p>".format(line.strip())
76
+ # html_content += "</body></html>"
77
+ # return html_content
78
+
79
+
80
+ # def deidentify_doc(pdftext, maxtokens, temperature, top_probability):
81
+ # prompt = "In the following text replace any person name and any address with term [redacted], replace any Date of Birth and NHS number with term [redacted]"
82
+ # # print('Prompt is ',prompt)
83
+ # # print('-------------------------------------------')
84
+ # output = model.create_chat_completion(
85
+ # messages=[
86
+ # {"role": "assistant", "content": prompt},
87
+ # {
88
+ # "role": "user",
89
+ # "content": pdftext
90
+ # }
91
+ # ],
92
+ # max_tokens=maxtokens,
93
+ # temperature=temperature
94
+ # )
95
+ # output = output['choices'][0]['message']['content']
96
+
97
+ # # print(prompt)
98
+ # # print(output)
99
+ # # print('-------------------------------------------------------')
100
+
101
+ # prompt = "Perform the following actions on given text: 1. Replace any person age with term [redacted] 2. DO NOT REPLACE ANY MEDICAL MEASUREMENTS 3. Replace only the CALENDAR DATES of format 'day/month/year' with term [redacted]"
102
+ # output = model.create_chat_completion(
103
+ # messages=[
104
+ # {"role": "assistant", "content": prompt},
105
+ # {
106
+ # "role": "user",
107
+ # "content": output
108
+ # }
109
+ # ],
110
+ # max_tokens=maxtokens,
111
+ # temperature=temperature
112
+ # )
113
+ # output = output['choices'][0]['message']['content']
114
+
115
+ # # print(prompt)
116
+ # # print(output)
117
+ # # print('-------------------------------------------------------')
118
+
119
+ # return output
120
+
121
+ # @spaces.GPU(duration=120)
122
+ # def pdf_to_text(files, maxtokens=2048, temperature=0, top_probability=0.95):
123
+ # files=[files]#remove later
124
+ # for file in files:
125
+ # file_name = os.path.basename(file)
126
+ # file_name_splt = file_name.split('.')
127
+ # # print('File name is ', file_name)
128
+ # if (len(file_name_splt) > 1 and file_name_splt[1] == 'pdf'):
129
+ # page2content = process_document(file, page_ids=[0])
130
+ # pdftext = page2content[1]
131
+ # # pdftext = file # remove later
132
+ # if (pdftext): #shift this if block to right later
133
+ # anonymized_text = deidentify_doc(pdftext, maxtokens, temperature, top_probability)
134
+ # return anonymized_text
135
+
136
+
137
+ # # model_id = "Meta-Llama-3-8B-Instruct.Q8_0.gguf"
138
+ # model_id = "models/Meta-Llama-3-8B-Instruct.Q8_0.gguf"
139
+ # model = Llama(model_path=model_id, n_ctx=2048, n_threads=8, n_gpu_layers=-1, n_batch=128)
140
+
141
+ # css = ".gradio-container {background: 'logo.png'}"
142
+ # temp_slider = gr.Slider(minimum=0, maximum=2, value=0.9, label="Temperature Value")
143
+ # prob_slider = gr.Slider(minimum=0, maximum=1, value=0.95, label="Max Probability Value")
144
+ # max_tokens = gr.Number(value=600, label="Max Tokens")
145
+ # input_folder = gr.File(file_count='multiple')
146
+ # input_folder_text = gr.Textbox(label='Enter output folder path')
147
+ # output_text = gr.Textbox()
148
+ # output_path_component = gr.File(label="Select Output Path")
149
+ # iface = gr.Interface(
150
+ # fn=pdf_to_text,
151
+ # inputs='file',
152
+ # # inputs=["textbox", input_folder_text, "textbox", max_tokens, temp_slider, prob_slider],
153
+ # outputs=output_text,
154
+ # title='COBIx Endoscopy Report De-Identification',
155
+ # description="This application assists to remove personal information from the uploaded clinical report",
156
+ # theme=gr.themes.Soft(),
157
+ # )
158
+ # iface.launch()
159
+
160
+ import os
161
+ from groq import Groq
162
+ import gradio as gr
163
+
164
+ client = Groq(api_key = os.environ.get("GROQ_API_KEY"), )
165
+
166
+ system_prompt = {
167
+ "role": "system",
168
+ "content":
169
+ "You are a useful assistant. You reply with efficient answers. "
170
+ }
171
+
172
+ async def chat_groq(message, history):
173
+
174
+ messages = [system_prompt]
175
+
176
+ for msg in history:
177
+ messages.append({"role": "user", "content": str(msg[0])})
178
+ messages.append({"role": "assistant", "content": str(msg[1])})
179
+
180
+ messages.append({"role": "user", "content": str (message)})
181
+
182
+ response_content = ''
183
+
184
+ stream = client.chat.completions.create(
185
+ model="llama3-8b-8192",
186
+ messages=messages,
187
+ max_tokens=1024,
188
+ temperature=1.3,
189
+ stream=True
190
+ )
191
+
192
+ for chunk in stream:
193
+ content = chunk.choices[0].delta.content
194
+ if content:
195
+ response_content += chunk. choices[0].delta.content
196
+ yield response_content
197
+
198
+ with gr. Blocks(theme=gr.themes.Monochrome(), fill_height=True) as demo:
199
+ gr.ChatInterface(chat_groq,
200
+ clear_btn=None,
201
+ undo_btn=None,
202
+ retry_btn=None,
203
+ )
204
+
205
+ demo.queue()
206
+ demo.launch()