srijaydeshpande commited on
Commit
6e7b7d8
·
1 Parent(s): 0f58c50

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +3 -61
app.py CHANGED
@@ -4,13 +4,8 @@ from tqdm import tqdm
4
  import re
5
  import gradio as gr
6
  import os
7
- # from gpt4all import GPT4All
8
- # import transformers
9
- # from transformers import GemmaTokenizer, AutoModelForCausalLM
10
- # from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
11
  import accelerate
12
  import spaces
13
- # import torch
14
  import subprocess
15
 
16
  subprocess.run('pip install llama-cpp-python==0.2.75 --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu124', shell=True)
@@ -26,7 +21,6 @@ def process_document(pdf_path, page_ids=None):
26
 
27
  page2content = {}
28
 
29
- # Process each extracted page
30
  for extracted_page in tqdm(extracted_pages):
31
  page_id = extracted_page.pageid
32
  content = process_page(extracted_page)
@@ -39,8 +33,6 @@ def process_page(extracted_page):
39
  elements = [element for element in extracted_page._objs]
40
  elements.sort(key=lambda a: a.y1, reverse=True)
41
  for i, element in enumerate(elements):
42
- # Extract text if the element is a text container
43
- # and text extraction is enabled
44
  if isinstance(element, LTTextContainer):
45
  line_text = extract_text_and_normalize(element)
46
  content.append(line_text)
@@ -53,18 +45,14 @@ def extract_text_and_normalize(element):
53
  norm_text = ''
54
  for line_text in line_texts:
55
  line_text=line_text.strip()
56
- # empty strings after striping convert to newline character
57
  if not line_text:
58
  line_text = '\n'
59
  else:
60
  line_text = re.sub('\s+', ' ', line_text)
61
- # if the last character is not a letter or number,
62
- # add newline character to a line
63
  if not re.search('[\w\d\,\-]', line_text[-1]):
64
  line_text+='\n'
65
  else:
66
  line_text+=' '
67
- # concatenate into single string
68
  norm_text+=line_text
69
  return norm_text
70
 
@@ -77,7 +65,7 @@ def txt_to_html(text):
77
 
78
  def deidentify_doc(pdftext="", prompt="", maxtokens=600, temperature=1.2, top_probability=0.95):
79
 
80
- prompt = "Please anonymize the following clinical note. Replace all the following information with the term '[redacted]': Redact any strings that might be a name or initials, patients’ names, doctors’ names, the names Dr., redact any medical staff names, redact any strings that might be a location or address, such as '3970 Longview Drive', redact any strings that look like 'age 37', redact any dates and registration numbers, redact professions such as 'manager', redact any contact information."
81
 
82
  output = model.create_chat_completion(
83
  messages = [
@@ -87,39 +75,11 @@ def deidentify_doc(pdftext="", prompt="", maxtokens=600, temperature=1.2, top_pr
87
  "content": pdftext
88
  }
89
  ],
90
- max_tokens=800,
91
- temperature=0
92
  )
93
  output = output['choices'][0]['message']['content']
94
 
95
- # if (pdftext):
96
- # prompt = prompt + ': ' + pdftext
97
- # output = model.generate(prompt=prompt, max_tokens=1024, n_batch=128)
98
-
99
- # messages = [
100
- # {"role": "assistant",
101
- # "content": prompt},
102
- # {"role": "user",
103
- # "content": pdftext}, ]
104
- # prompt = model.tokenizer.apply_chat_template(
105
- # messages,
106
- # tokenize=False,
107
- # add_generation_prompt=True
108
- # )
109
- # terminators = [
110
- # model.tokenizer.eos_token_id,
111
- # model.tokenizer.convert_tokens_to_ids("<|eot_id|>")
112
- # ]
113
- # outputs = model(
114
- # prompt,
115
- # max_new_tokens=maxtokens,
116
- # eos_token_id=terminators,
117
- # do_sample=True,
118
- # temperature=temperature,
119
- # top_p=top_probability,
120
- # )
121
- # output = outputs[0]["generated_text"][len(prompt):]
122
-
123
  return output
124
 
125
  def mkdir(dir):
@@ -139,29 +99,11 @@ def pdf_to_text(files, output_folder, prompt, maxtokens=600, temperature=1.2, to
139
  pdftext = page2content[1]
140
  if(pdftext):
141
  anonymized_text = deidentify_doc(pdftext, prompt, maxtokens, temperature, top_probability)
142
- # html = txt_to_html(display_text)
143
- # with open('out.html', "w", encoding="utf-8") as file:
144
- # file.write(html)
145
- # with open(os.path.join(output_folder, file_name_splt[0]+'.txt'), 'w') as file:
146
- # # Write some text to the file
147
- # file.write(anonymized_text)
148
- display_text = "All selected reports are anonymized and results are saved in " + output_folder
149
  return anonymized_text
150
 
151
  model_id = "Meta-Llama-3-8B-Instruct.Q5_K_M.gguf"
152
  model = Llama(model_path=model_id, n_ctx=2048, n_threads=8, n_gpu_layers=81, n_batch=64)
153
 
154
- # model = GPT4All("Meta-Llama-3-8B-Instruct.Q4_0.gguf", n_threads=8, device='gpu')
155
- # model.chat_session()
156
-
157
- # model_id = "Meta-Llama-3-8B-Instruct"
158
- # model = transformers.pipeline(
159
- # "text-generation",
160
- # model=model_id,
161
- # model_kwargs={"torch_dtype": torch.bfloat16},
162
- # device="cuda",
163
- # )
164
-
165
  css = ".gradio-container {background: 'logo.png'}"
166
  temp_slider = gr.Slider(minimum=0, maximum=2, value=0.2, label="Temperature Value")
167
  prob_slider = gr.Slider(minimum=0, maximum=1, value=0.95, label="Max Probability Value")
 
4
  import re
5
  import gradio as gr
6
  import os
 
 
 
 
7
  import accelerate
8
  import spaces
 
9
  import subprocess
10
 
11
  subprocess.run('pip install llama-cpp-python==0.2.75 --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu124', shell=True)
 
21
 
22
  page2content = {}
23
 
 
24
  for extracted_page in tqdm(extracted_pages):
25
  page_id = extracted_page.pageid
26
  content = process_page(extracted_page)
 
33
  elements = [element for element in extracted_page._objs]
34
  elements.sort(key=lambda a: a.y1, reverse=True)
35
  for i, element in enumerate(elements):
 
 
36
  if isinstance(element, LTTextContainer):
37
  line_text = extract_text_and_normalize(element)
38
  content.append(line_text)
 
45
  norm_text = ''
46
  for line_text in line_texts:
47
  line_text=line_text.strip()
 
48
  if not line_text:
49
  line_text = '\n'
50
  else:
51
  line_text = re.sub('\s+', ' ', line_text)
 
 
52
  if not re.search('[\w\d\,\-]', line_text[-1]):
53
  line_text+='\n'
54
  else:
55
  line_text+=' '
 
56
  norm_text+=line_text
57
  return norm_text
58
 
 
65
 
66
  def deidentify_doc(pdftext="", prompt="", maxtokens=600, temperature=1.2, top_probability=0.95):
67
 
68
+ # prompt = "Please anonymize the following clinical note. Replace all the following information with the term '[redacted]': Redact any strings that might be a name or initials, patients’ names, doctors’ names, the names Dr., redact any medical staff names, redact any strings that might be a location or address, such as '3970 Longview Drive', redact any strings that look like 'age 37', redact any dates and registration numbers, redact professions such as 'manager', redact any contact information."
69
 
70
  output = model.create_chat_completion(
71
  messages = [
 
75
  "content": pdftext
76
  }
77
  ],
78
+ max_tokens=maxtokens,
79
+ temperature=temperature
80
  )
81
  output = output['choices'][0]['message']['content']
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  return output
84
 
85
  def mkdir(dir):
 
99
  pdftext = page2content[1]
100
  if(pdftext):
101
  anonymized_text = deidentify_doc(pdftext, prompt, maxtokens, temperature, top_probability)
 
 
 
 
 
 
 
102
  return anonymized_text
103
 
104
  model_id = "Meta-Llama-3-8B-Instruct.Q5_K_M.gguf"
105
  model = Llama(model_path=model_id, n_ctx=2048, n_threads=8, n_gpu_layers=81, n_batch=64)
106
 
 
 
 
 
 
 
 
 
 
 
 
107
  css = ".gradio-container {background: 'logo.png'}"
108
  temp_slider = gr.Slider(minimum=0, maximum=2, value=0.2, label="Temperature Value")
109
  prob_slider = gr.Slider(minimum=0, maximum=1, value=0.95, label="Max Probability Value")