srijaydeshpande commited on
Commit
80f19e7
·
1 Parent(s): 1838b96

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -177
app.py CHANGED
@@ -1,188 +1,115 @@
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, InferenceClient
11
- # from llama_cpp import Llama
12
 
13
- # from huggingface_hub import login
14
- # login(token = os.getenv('HF_TOKEN'))
15
 
16
- # repo_id = "srijaydeshpande/Deid-Fine-Tuned"
17
- # model_id = "deid_finetuned.Q4_K_M.gguf"
18
 
 
 
 
 
 
 
 
 
 
19
 
20
- # hf_hub_download(
21
- # repo_id="srijaydeshpande/Deid-Fine-Tuned",
22
- # filename="deid_finetuned.Q4_K_M.gguf",
23
- # local_dir = "./models"
24
- # )
25
 
26
- def process_document(pdf_path):
27
- extracted_pages = extract_pages(pdf_path)
28
- page2content = {}
29
- for extracted_page in tqdm(extracted_pages):
30
- page_id = extracted_page.pageid
31
- content = process_page(extracted_page)
32
- page2content[page_id] = content
33
- return page2content
34
 
 
 
 
 
 
35
 
36
- def process_page(extracted_page):
37
  content = []
38
- elements = [element for element in extracted_page._objs]
39
- elements.sort(key=lambda a: a.y1, reverse=True)
40
- for i, element in enumerate(elements):
41
- if isinstance(element, LTTextContainer):
42
- line_text = extract_text_and_normalize(element)
43
- content.append(line_text)
44
- content = re.sub('\n+', '\n', ''.join(content))
45
- return content
46
-
47
-
48
- def extract_text_and_normalize(element):
49
- # Extract text from line and split it with new lines
50
- line_texts = element.get_text().split('\n')
51
- norm_text = ''
52
- for line_text in line_texts:
53
- line_text = line_text.strip()
54
- if not line_text:
55
- line_text = '\n'
56
- else:
57
- line_text = re.sub('\s+', ' ', line_text)
58
- if not re.search('[\w\d\,\-]', line_text[-1]):
59
- line_text += '\n'
60
- else:
61
- line_text += ' '
62
- norm_text += line_text
63
- return norm_text
64
-
65
-
66
- def txt_to_html(text):
67
- html_content = "<html><body>"
68
- for line in text.split('\n'):
69
- html_content += "<p>{}</p>".format(line.strip())
70
- html_content += "</body></html>"
71
- return html_content
72
-
73
- def deidentify_doc(llm_type, pdftext, maxtokens, temperature, top_probability):
74
-
75
- prompt = "In the following text, perform the following actions: 1. Replace only the calendar dates with term [date]. Example: if input is 'Date of birth: 15/5/1959 calculated BP (Systolic 158.00 mm, Diastolic 124.95 mm)' output should be 'Date of birth: [date] calculated BP (Systolic 158.00 mm, Diastolic 124.95 mm)' 2. Replace location or address, such as '3970 Longview Drive, CV36HE' with term [address]. Replace complete GP address, such as 'Phanton Medical Centre, Birmingham, CV36HE' with term [address]. It is important that all addresses are completely replaced with [address]. 3. Replace any person name with term [name]. It is important that all person names are replaced with term [name]. Remove any gender terms 'male' or 'female' if exists. 4. Replace the nhs number and the case note number with term [ID]. Replace Hospital number with [ID]. 4. Replace age of person with [age]. It is important that all age numbers are completely replaced with [age]."
76
-
77
- if(llm_type == 'Fine tuned LLama3'):
78
-
79
- llm = Llama(
80
- model_path="models/" + model_id,
81
- flash_attn=True,
82
- n_gpu_layers=81,
83
- n_batch=1024,
84
- n_ctx=8192,
85
- )
86
-
87
- output = llm.create_chat_completion(
88
- messages=[
89
- {"from": "user", "value": prompt + ' Text: ' + pdftext},
90
- ],
91
- max_tokens=maxtokens,
92
- temperature=temperature
93
- )
94
- output = output['choices'][0]['message']['content']
95
-
96
- # Remove starting header string in output
97
- find_index = output.find(' '.join(pdftext.split()[:3]))
98
- if find_index != -1:
99
- output = output[find_index:].strip()
100
-
101
- last_index = output.rfind(' '.join(pdftext.split()[-3:]))
102
- if last_index != -1:
103
- output = output[:last_index].strip()
104
-
105
- output = llm.create_chat_completion(
106
- messages=[
107
- {"from": "user", "value": prompt + ' Text: ' + output},
108
- ],
109
- max_tokens=maxtokens,
110
- temperature=temperature
111
  )
112
- output = output['choices'][0]['message']['content']
113
-
114
- # Remove starting header string in output
115
- find_index = output.find(' '.join(pdftext.split()[:3]))
116
- if find_index != -1:
117
- output = output[find_index:].strip()
118
-
119
- last_text_to_find = ' '.join(pdftext.split()[-2:])
120
- last_index = output.rfind(last_text_to_find)
121
- if last_index != -1 and last_index>(len(pdftext)/2):
122
- output = output[:last_index+len(last_text_to_find)].strip()
123
- yield output
124
-
125
- else:
126
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
127
- messages = [{"role": "assistant", "content": prompt}]
128
- messages.append({"role": "user", "content": pdftext})
129
- response = ""
130
- for message in client.chat_completion(
131
- messages,
132
- max_tokens=max_tokens,
133
- temperature=temperature,
134
- top_p=top_probability,
135
- ):
136
- # token = message.choices[0].delta.content
137
- token = message['choices'][0]['message']['content']
138
- print('RESPONSE IS ',token)
139
-
140
- response += token
141
-
142
- return response
143
-
144
-
145
- # @spaces.GPU(duration=80)
146
- def pdf_to_text(files, llm_type, maxtokens=2048, temperature=0, top_probability=0.95):
147
- files=[files]
148
- for file in files:
149
- if not file:
150
- return 'Please provide a valid PDF'
151
- file_name = os.path.basename(file)
152
- file_name_splt = file_name.split('.')
153
- accumulated_text = "" # Store streamed data
154
- if (len(file_name_splt) > 1 and file_name_splt[1] == 'pdf'):
155
- page2content = process_document(file)
156
- anonymized_text = ''
157
- original_pdf_text = ''
158
- for page_id in page2content:
159
- pdftext = page2content[page_id]
160
- original_pdf_text += pdftext + '\n'
161
- # response_generator = deidentify_doc(llm_type, pdftext, maxtokens, temperature, top_probability)
162
- # print('RESPONSE GENERATOR IS ',response_generator)
163
- # for chunk in response_generator:
164
- # accumulated_text += chunk
165
- # yield accumulated_text # Keep updating output
166
- # return response_generator # + "\n\n"
167
- print('Extracted Page Content Is ', original_pdf_text)
168
- print('------------------------------------------------------------')
169
- # return anonymized_text
170
-
171
- css = ".gradio-container {background: 'logo.png'}"
172
- temp_slider = gr.Slider(minimum=0, maximum=2, value=0.9, label="Temperature Value")
173
- prob_slider = gr.Slider(minimum=0, maximum=1, value=0.95, label="Max Probability Value")
174
- max_tokens = gr.Number(value=600, label="Max Tokens")
175
- input_folder = gr.File(file_count='multiple')
176
- input_folder_text = gr.Textbox(label='Enter output folder path')
177
- output_text = gr.Textbox()
178
- output_path_component = gr.File(label="Select Output Path")
179
- llm_type = gr.Radio(["Fine tuned LLama3", "Zephyr-7B-β"])
180
- iface = gr.Interface(
181
- fn=pdf_to_text,
182
- inputs=['file', llm_type],
183
- outputs=gr.Textbox(),
184
- title='Histofy EndoDeID (Endoscopy Report De-Identification)',
185
- description="This application assists to remove personal information from the uploaded clinical report",
186
- theme=gr.themes.Soft(),
187
  )
188
- iface.launch()
 
 
1
+ import torch
 
 
 
2
  import gradio as gr
3
+ from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
 
 
 
 
 
4
 
5
+ MODEL_NAME = "Qwen/Qwen2.5-VL-3B-Instruct"
 
6
 
7
+ print("Loading model...")
 
8
 
9
+ model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
10
+ MODEL_NAME,
11
+ torch_dtype=torch.float16,
12
+ device_map="auto"
13
+ )
14
+
15
+ processor = AutoProcessor.from_pretrained(MODEL_NAME)
16
+
17
+ print("Model loaded.")
18
 
19
+ def detect_covering(ref1, ref2, ref3, query):
 
 
 
 
20
 
21
+ refs = [img for img in [ref1, ref2, ref3] if img is not None]
 
 
 
 
 
 
 
22
 
23
+ if len(refs) == 0:
24
+ return "Please upload at least one reference image."
25
+
26
+ if query is None:
27
+ return "Please upload query image."
28
 
 
29
  content = []
30
+
31
+ # Reference images
32
+ for ref in refs:
33
+ content.append({
34
+ "type": "image",
35
+ "image": ref
36
+ })
37
+
38
+ # Query image
39
+ content.append({
40
+ "type": "image",
41
+ "image": query
42
+ })
43
+
44
+ # Prompt
45
+ content.append({
46
+ "type": "text",
47
+ "text": """
48
+ Reference images show a cylindrical tree protector / tree covering.
49
+
50
+ Determine whether the LAST image contains the same type of cylindrical tree covering anywhere in the image.
51
+
52
+ Answer ONLY:
53
+ YES
54
+ or
55
+ NO
56
+
57
+ If uncertain, answer NO.
58
+ """
59
+ })
60
+
61
+ messages = [
62
+ {
63
+ "role": "user",
64
+ "content": content
65
+ }
66
+ ]
67
+
68
+ text = processor.apply_chat_template(
69
+ messages,
70
+ tokenize=False,
71
+ add_generation_prompt=True
72
+ )
73
+
74
+ inputs = processor(
75
+ text=[text],
76
+ images=refs + [query],
77
+ return_tensors="pt",
78
+ padding=True
79
+ )
80
+
81
+ inputs = inputs.to(model.device)
82
+
83
+ with torch.no_grad():
84
+ generated_ids = model.generate(
85
+ **inputs,
86
+ max_new_tokens=5,
87
+ do_sample=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  )
89
+
90
+ output_text = processor.batch_decode(
91
+ generated_ids,
92
+ skip_special_tokens=True
93
+ )[0]
94
+
95
+ output_text = output_text.upper()
96
+
97
+ if "YES" in output_text:
98
+ return "YES"
99
+
100
+ return "NO"
101
+
102
+ demo = gr.Interface(
103
+ fn=detect_covering,
104
+ inputs=[
105
+ gr.Image(type="pil", label="Reference Image 1"),
106
+ gr.Image(type="pil", label="Reference Image 2"),
107
+ gr.Image(type="pil", label="Reference Image 3"),
108
+ gr.Image(type="pil", label="Query Image")
109
+ ],
110
+ outputs=gr.Textbox(label="Prediction"),
111
+ title="Tree Covering Detector",
112
+ description="Few-shot visual detection using Qwen2.5-VL"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  )
114
+
115
+ demo.launch()