srijaydeshpande commited on
Commit
1272fbc
·
1 Parent(s): d626e1a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +365 -360
app.py CHANGED
@@ -1,383 +1,388 @@
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/Meta-Llama-3-70B-Instruct-GGUF",
25
- # filename="Meta-Llama-3-70B-Instruct-Q3_K_M.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 = "models/Meta-Llama-3-70B-Instruct-Q3_K_M.gguf"
138
- # # model = Llama(model_path=model_id, n_ctx=2048, n_threads=8, n_gpu_layers=-1, n_batch=128)
139
- # model = Llama(
140
- # model_path=model_id,
141
- # flash_attn=True,
142
- # n_gpu_layers=81,
143
- # n_batch=1024,
144
- # n_ctx=8192,
145
- # )
146
-
147
- # css = ".gradio-container {background: 'logo.png'}"
148
- # temp_slider = gr.Slider(minimum=0, maximum=2, value=0.9, label="Temperature Value")
149
- # prob_slider = gr.Slider(minimum=0, maximum=1, value=0.95, label="Max Probability Value")
150
- # max_tokens = gr.Number(value=600, label="Max Tokens")
151
- # input_folder = gr.File(file_count='multiple')
152
- # input_folder_text = gr.Textbox(label='Enter output folder path')
153
- # output_text = gr.Textbox()
154
- # output_path_component = gr.File(label="Select Output Path")
155
- # iface = gr.Interface(
156
- # fn=pdf_to_text,
157
- # inputs='file',
158
- # # inputs=["textbox", input_folder_text, "textbox", max_tokens, temp_slider, prob_slider],
159
- # outputs=output_text,
160
- # title='COBIx Endoscopy Report De-Identification',
161
- # description="This application assists to remove personal information from the uploaded clinical report",
162
- # theme=gr.themes.Soft(),
163
- # )
164
- # iface.launch()
165
-
166
  import spaces
167
- import json
168
  import subprocess
 
169
  from llama_cpp import Llama
170
  from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
171
  from llama_cpp_agent.providers import LlamaCppPythonProvider
172
  from llama_cpp_agent.chat_history import BasicChatHistory
173
  from llama_cpp_agent.chat_history.messages import Roles
174
- import gradio as gr
175
- from huggingface_hub import hf_hub_download
 
 
 
 
 
 
 
 
176
 
177
  hf_hub_download(
178
  repo_id="bartowski/Meta-Llama-3-70B-Instruct-GGUF",
179
  filename="Meta-Llama-3-70B-Instruct-Q3_K_M.gguf",
180
  local_dir = "./models"
181
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  # hf_hub_download(
183
- # repo_id="bartowski/Mistral-7B-Instruct-v0.3-GGUF",
184
- # filename="Mistral-7B-Instruct-v0.3-f32.gguf",
185
  # local_dir = "./models"
186
  # )
 
 
 
 
 
187
 
188
- css = """
189
- .message-row {
190
- justify-content: space-evenly !important;
191
- }
192
- .message-bubble-border {
193
- border-radius: 6px !important;
194
- }
195
- .message-buttons-bot, .message-buttons-user {
196
- right: 10px !important;
197
- left: auto !important;
198
- bottom: 2px !important;
199
- }
200
- .dark.message-bubble-border {
201
- border-color: #343140 !important;
202
- }
203
- .dark.user {
204
- background: #1e1c26 !important;
205
- }
206
- .dark.assistant.dark, .dark.pending.dark {
207
- background: #16141c !important;
208
- }
209
- """
210
-
211
- def get_messages_formatter_type(model_name):
212
- if "Llama" in model_name:
213
- return MessagesFormatterType.LLAMA_3
214
- elif "Mistral" in model_name:
215
- return MessagesFormatterType.MISTRAL
216
- else:
217
- raise ValueError(f"Unsupported model: {model_name}")
218
 
219
- @spaces.GPU(duration=120)
220
- def respond(
221
- message,
222
- history: list[tuple[str, str]],
223
- model,
224
- system_message,
225
- max_tokens,
226
- temperature,
227
- top_p,
228
- top_k,
229
- repeat_penalty,
230
- ):
231
- chat_template = get_messages_formatter_type(model)
232
-
233
- llm = Llama(
234
- model_path=f"models/{model}",
235
- flash_attn=True,
236
- n_gpu_layers=81,
237
- n_batch=1024,
238
- n_ctx=8192,
239
- )
240
- provider = LlamaCppPythonProvider(llm)
241
 
242
- agent = LlamaCppAgent(
243
- provider,
244
- system_prompt=f"{system_message}",
245
- predefined_messages_formatter_type=chat_template,
246
- debug_output=True
247
- )
248
 
249
- settings = provider.get_provider_default_settings()
250
- settings.temperature = temperature
251
- settings.top_k = top_k
252
- settings.top_p = top_p
253
- settings.max_tokens = max_tokens
254
- settings.repeat_penalty = repeat_penalty
255
- settings.stream = True
256
-
257
- messages = BasicChatHistory()
258
-
259
- for msn in history:
260
- user = {
261
- 'role': Roles.user,
262
- 'content': msn[0]
263
- }
264
- assistant = {
265
- 'role': Roles.assistant,
266
- 'content': msn[1]
267
- }
268
- messages.add_message(user)
269
- messages.add_message(assistant)
270
 
271
- stream = agent.get_chat_response(
272
- message,
273
- llm_sampling_settings=settings,
274
- chat_history=messages,
275
- returns_streaming_generator=True,
276
- print_output=False
277
- )
278
 
279
- outputs = ""
280
- for output in stream:
281
- outputs += output
282
- yield outputs
283
-
284
- PLACEHOLDER = """
285
- <div class="message-bubble-border" style="display:flex; max-width: 600px; border-radius: 6px; border-width: 1px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); backdrop-filter: blur(10px);">
286
- <figure style="margin: 0;">
287
- <img src="https://huggingface.co/spaces/pabloce/llama-cpp-agent/resolve/main/llama.jpg" alt="Logo" style="width: 100%; height: 100%; border-radius: 8px;">
288
- </figure>
289
- <div style="padding: .5rem 1.5rem;">
290
- <h2 style="text-align: left; font-size: 1.5rem; font-weight: 700; margin-bottom: 0.5rem;">llama-cpp-agent</h2>
291
- <p style="text-align: left; font-size: 16px; line-height: 1.5; margin-bottom: 15px;">The llama-cpp-agent framework simplifies interactions with Large Language Models (LLMs), providing an interface for chatting, executing function calls, generating structured output, performing retrieval augmented generation, and processing text using agentic chains with tools.</p>
292
- <div style="display: flex; justify-content: space-between; align-items: center;">
293
- <div style="display: flex; flex-flow: column; justify-content: space-between;">
294
- <span style="display: inline-flex; align-items: center; border-radius: 0.375rem; background-color: rgba(229, 70, 77, 0.1); padding: 0.1rem 0.75rem; font-size: 0.75rem; font-weight: 500; color: #f88181; margin-bottom: 2.5px;">
295
- Mistral 7B Instruct v0.3
296
- </span>
297
- <span style="display: inline-flex; align-items: center; border-radius: 0.375rem; background-color: rgba(79, 70, 229, 0.1); padding: 0.1rem 0.75rem; font-size: 0.75rem; font-weight: 500; color: #60a5fa; margin-top: 2.5px;">
298
- Meta Llama 3 70B Instruct
299
- </span>
300
- </div>
301
- <div style="display: flex; justify-content: flex-end; align-items: center;">
302
- <a href="https://discord.gg/sRMvWKrh" target="_blank" rel="noreferrer" style="padding: .5rem;">
303
- <svg width="24" height="24" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 5 30.67 23.25">
304
- <title>Discord</title>
305
- <path d="M26.0015 6.9529C24.0021 6.03845 21.8787 5.37198 19.6623 5C19.3833 5.48048 19.0733 6.13144 18.8563 6.64292C16.4989 6.30193 14.1585 6.30193 11.8336 6.64292C11.6166 6.13144 11.2911 5.48048 11.0276 5C8.79575 5.37198 6.67235 6.03845 4.6869 6.9529C0.672601 12.8736 -0.41235 18.6548 0.130124 24.3585C2.79599 26.2959 5.36889 27.4739 7.89682 28.2489C8.51679 27.4119 9.07477 26.5129 9.55525 25.5675C8.64079 25.2265 7.77283 24.808 6.93587 24.312C7.15286 24.1571 7.36986 23.9866 7.57135 23.8161C12.6241 26.1255 18.0969 26.1255 23.0876 23.8161C23.3046 23.9866 23.5061 24.1571 23.7231 24.312C22.8861 24.808 22.0182 25.2265 21.1037 25.5675C21.5842 26.5129 22.1422 27.4119 22.7621 28.2489C25.2885 27.4739 27.8769 26.2959 30.5288 24.3585C31.1952 17.7559 29.4733 12.0212 26.0015 6.9529ZM10.2527 20.8402C8.73376 20.8402 7.49382 19.4608 7.49382 17.7714C7.49382 16.082 8.70276 14.7025 10.2527 14.7025C11.7871 14.7025 13.0425 16.082 13.0115 17.7714C13.0115 19.4608 11.7871 20.8402 10.2527 20.8402ZM20.4373 20.8402C18.9183 20.8402 17.6768 19.4608 17.6768 17.7714C17.6768 16.082 18.8873 14.7025 20.4373 14.7025C21.9717 14.7025 23.2271 16.082 23.1961 17.7714C23.1961 19.4608 21.9872 20.8402 20.4373 20.8402Z"></path>
306
- </svg>
307
- </a>
308
- <a href="https://github.com/Maximilian-Winter/llama-cpp-agent" target="_blank" rel="noreferrer" style="padding: .5rem;">
309
- <svg width="24" height="24" fill="currentColor" viewBox="3 3 18 18">
310
- <title>GitHub</title>
311
- <path d="M12 3C7.0275 3 3 7.12937 3 12.2276C3 16.3109 5.57625 19.7597 9.15374 20.9824C9.60374 21.0631 9.77249 20.7863 9.77249 20.5441C9.77249 20.3249 9.76125 19.5982 9.76125 18.8254C7.5 19.2522 6.915 18.2602 6.735 17.7412C6.63375 17.4759 6.19499 16.6569 5.8125 16.4378C5.4975 16.2647 5.0475 15.838 5.80124 15.8264C6.51 15.8149 7.01625 16.4954 7.18499 16.7723C7.99499 18.1679 9.28875 17.7758 9.80625 17.5335C9.885 16.9337 10.1212 16.53 10.38 16.2993C8.3775 16.0687 6.285 15.2728 6.285 11.7432C6.285 10.7397 6.63375 9.9092 7.20749 9.26326C7.1175 9.03257 6.8025 8.08674 7.2975 6.81794C7.2975 6.81794 8.05125 6.57571 9.77249 7.76377C10.4925 7.55615 11.2575 7.45234 12.0225 7.45234C12.7875 7.45234 13.5525 7.55615 14.2725 7.76377C15.9937 6.56418 16.7475 6.81794 16.7475 6.81794C17.2424 8.08674 16.9275 9.03257 16.8375 9.26326C17.4113 9.9092 17.76 10.7281 17.76 11.7432C17.76 15.2843 15.6563 16.0687 13.6537 16.2993C13.98 16.5877 14.2613 17.1414 14.2613 18.0065C14.2613 19.2407 14.25 20.2326 14.25 20.5441C14.25 20.7863 14.4188 21.0746 14.8688 20.9824C16.6554 20.364 18.2079 19.1866 19.3078 17.6162C20.4077 16.0457 20.9995 14.1611 21 12.2276C21 7.12937 16.9725 3 12 3Z"></path>
312
- </svg>
313
- </a>
314
- </div>
315
- </div>
316
- </div>
317
- </div>
318
- """
319
-
320
- demo = gr.ChatInterface(
321
- respond,
322
- additional_inputs=[
323
- gr.Dropdown([
324
- 'Meta-Llama-3-70B-Instruct-Q3_K_M.gguf',
325
- 'Mistral-7B-Instruct-v0.3-f32.gguf'
326
- ],
327
- value="Meta-Llama-3-70B-Instruct-Q3_K_M.gguf",
328
- label="Model"
329
- ),
330
- gr.Textbox(value="You are a helpful assistant.", label="System message"),
331
- gr.Slider(minimum=1, maximum=4096, value=2048, step=1, label="Max tokens"),
332
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
333
- gr.Slider(
334
- minimum=0.1,
335
- maximum=1.0,
336
- value=0.95,
337
- step=0.05,
338
- label="Top-p",
339
- ),
340
- gr.Slider(
341
- minimum=0,
342
- maximum=100,
343
- value=40,
344
- step=1,
345
- label="Top-k",
346
- ),
347
- gr.Slider(
348
- minimum=0.0,
349
- maximum=2.0,
350
- value=1.1,
351
- step=0.1,
352
- label="Repetition penalty",
353
- ),
354
- ],
355
- theme=gr.themes.Soft(primary_hue="violet", secondary_hue="violet", neutral_hue="gray",font=[gr.themes.GoogleFont("Exo"), "ui-sans-serif", "system-ui", "sans-serif"]).set(
356
- body_background_fill_dark="#16141c",
357
- block_background_fill_dark="#16141c",
358
- block_border_width="1px",
359
- block_title_background_fill_dark="#1e1c26",
360
- input_background_fill_dark="#292733",
361
- button_secondary_background_fill_dark="#24212b",
362
- border_color_accent_dark="#343140",
363
- border_color_primary_dark="#343140",
364
- background_fill_secondary_dark="#16141c",
365
- color_accent_soft_dark="transparent",
366
- code_background_fill_dark="#292733",
367
- ),
368
- css=css,
369
- retry_btn="Retry",
370
- undo_btn="Undo",
371
- clear_btn="Clear",
372
- submit_btn="Send",
373
- description="Llama-cpp-agent: Chat multi llm selection",
374
- chatbot=gr.Chatbot(
375
- scale=1,
376
- placeholder=PLACEHOLDER,
377
- likeable=False,
378
- show_copy_button=True
379
- )
380
- )
381
 
382
- if __name__ == "__main__":
383
- demo.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
  from llama_cpp import Llama
12
  from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
13
  from llama_cpp_agent.providers import LlamaCppPythonProvider
14
  from llama_cpp_agent.chat_history import BasicChatHistory
15
  from llama_cpp_agent.chat_history.messages import Roles
16
+
17
+ # subprocess.run('pip install llama-cpp-python==0.2.75 --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu124', shell=True)
18
+ # subprocess.run('pip install llama-cpp-agent==0.2.10', shell=True)
19
+
20
+
21
+ # hf_hub_download(
22
+ # repo_id="QuantFactory/Meta-Llama-3-8B-Instruct-GGUF",
23
+ # filename="Meta-Llama-3-8B-Instruct.Q8_0.gguf",
24
+ # local_dir = "./models"
25
+ # )
26
 
27
  hf_hub_download(
28
  repo_id="bartowski/Meta-Llama-3-70B-Instruct-GGUF",
29
  filename="Meta-Llama-3-70B-Instruct-Q3_K_M.gguf",
30
  local_dir = "./models"
31
  )
32
+
33
+ def process_document(pdf_path, page_ids=None):
34
+ extracted_pages = extract_pages(pdf_path, page_numbers=page_ids)
35
+
36
+ page2content = {}
37
+
38
+ for extracted_page in tqdm(extracted_pages):
39
+ page_id = extracted_page.pageid
40
+ content = process_page(extracted_page)
41
+ page2content[page_id] = content
42
+
43
+ return page2content
44
+
45
+
46
+ def process_page(extracted_page):
47
+ content = []
48
+ elements = [element for element in extracted_page._objs]
49
+ elements.sort(key=lambda a: a.y1, reverse=True)
50
+ for i, element in enumerate(elements):
51
+ if isinstance(element, LTTextContainer):
52
+ line_text = extract_text_and_normalize(element)
53
+ content.append(line_text)
54
+ content = re.sub('\n+', ' ', ''.join(content))
55
+ return content
56
+
57
+
58
+ def extract_text_and_normalize(element):
59
+ # Extract text from line and split it with new lines
60
+ line_texts = element.get_text().split('\n')
61
+ norm_text = ''
62
+ for line_text in line_texts:
63
+ line_text = line_text.strip()
64
+ if not line_text:
65
+ line_text = '\n'
66
+ else:
67
+ line_text = re.sub('\s+', ' ', line_text)
68
+ if not re.search('[\w\d\,\-]', line_text[-1]):
69
+ line_text += '\n'
70
+ else:
71
+ line_text += ' '
72
+ norm_text += line_text
73
+ return norm_text
74
+
75
+
76
+ def txt_to_html(text):
77
+ html_content = "<html><body>"
78
+ for line in text.split('\n'):
79
+ html_content += "<p>{}</p>".format(line.strip())
80
+ html_content += "</body></html>"
81
+ return html_content
82
+
83
+
84
+ def deidentify_doc(pdftext, maxtokens, temperature, top_probability):
85
+ 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]"
86
+ # print('Prompt is ',prompt)
87
+ # print('-------------------------------------------')
88
+
89
+ model_id = "models/Meta-Llama-3-70B-Instruct-Q3_K_M.gguf"
90
+ # model = Llama(model_path=model_id, n_ctx=2048, n_threads=8, n_gpu_layers=-1, n_batch=128)
91
+ model = Llama(
92
+ model_path=model_id,
93
+ flash_attn=True,
94
+ n_gpu_layers=81,
95
+ n_batch=1024,
96
+ n_ctx=8192,
97
+ )
98
+
99
+ output = model.create_chat_completion(
100
+ messages=[
101
+ {"role": "assistant", "content": prompt},
102
+ {
103
+ "role": "user",
104
+ "content": pdftext
105
+ }
106
+ ],
107
+ max_tokens=maxtokens,
108
+ temperature=temperature
109
+ )
110
+ output = output['choices'][0]['message']['content']
111
+
112
+ # print(prompt)
113
+ # print(output)
114
+ # print('-------------------------------------------------------')
115
+
116
+ 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]"
117
+ output = model.create_chat_completion(
118
+ messages=[
119
+ {"role": "assistant", "content": prompt},
120
+ {
121
+ "role": "user",
122
+ "content": output
123
+ }
124
+ ],
125
+ max_tokens=maxtokens,
126
+ temperature=temperature
127
+ )
128
+ output = output['choices'][0]['message']['content']
129
+
130
+ # print(prompt)
131
+ # print(output)
132
+ # print('-------------------------------------------------------')
133
+
134
+ return output
135
+
136
+ @spaces.GPU(duration=120)
137
+ def pdf_to_text(files, maxtokens=2048, temperature=0, top_probability=0.95):
138
+ files=[files]#remove later
139
+ for file in files:
140
+ file_name = os.path.basename(file)
141
+ file_name_splt = file_name.split('.')
142
+ # print('File name is ', file_name)
143
+ if (len(file_name_splt) > 1 and file_name_splt[1] == 'pdf'):
144
+ page2content = process_document(file, page_ids=[0])
145
+ pdftext = page2content[1]
146
+ # pdftext = file # remove later
147
+ if (pdftext): #shift this if block to right later
148
+ anonymized_text = deidentify_doc(pdftext, maxtokens, temperature, top_probability)
149
+ return anonymized_text
150
+
151
+
152
+ css = ".gradio-container {background: 'logo.png'}"
153
+ temp_slider = gr.Slider(minimum=0, maximum=2, value=0.9, label="Temperature Value")
154
+ prob_slider = gr.Slider(minimum=0, maximum=1, value=0.95, label="Max Probability Value")
155
+ max_tokens = gr.Number(value=600, label="Max Tokens")
156
+ input_folder = gr.File(file_count='multiple')
157
+ input_folder_text = gr.Textbox(label='Enter output folder path')
158
+ output_text = gr.Textbox()
159
+ output_path_component = gr.File(label="Select Output Path")
160
+ iface = gr.Interface(
161
+ fn=pdf_to_text,
162
+ inputs='file',
163
+ # inputs=["textbox", input_folder_text, "textbox", max_tokens, temp_slider, prob_slider],
164
+ outputs=output_text,
165
+ title='COBIx Endoscopy Report De-Identification',
166
+ description="This application assists to remove personal information from the uploaded clinical report",
167
+ theme=gr.themes.Soft(),
168
+ )
169
+ iface.launch()
170
+
171
+ # import spaces
172
+ # import json
173
+ # import subprocess
174
+ # from llama_cpp import Llama
175
+ # from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
176
+ # from llama_cpp_agent.providers import LlamaCppPythonProvider
177
+ # from llama_cpp_agent.chat_history import BasicChatHistory
178
+ # from llama_cpp_agent.chat_history.messages import Roles
179
+ # import gradio as gr
180
+ # from huggingface_hub import hf_hub_download
181
+
182
  # hf_hub_download(
183
+ # repo_id="bartowski/Meta-Llama-3-70B-Instruct-GGUF",
184
+ # filename="Meta-Llama-3-70B-Instruct-Q3_K_M.gguf",
185
  # local_dir = "./models"
186
  # )
187
+ # # hf_hub_download(
188
+ # # repo_id="bartowski/Mistral-7B-Instruct-v0.3-GGUF",
189
+ # # filename="Mistral-7B-Instruct-v0.3-f32.gguf",
190
+ # # local_dir = "./models"
191
+ # # )
192
 
193
+ # css = """
194
+ # .message-row {
195
+ # justify-content: space-evenly !important;
196
+ # }
197
+ # .message-bubble-border {
198
+ # border-radius: 6px !important;
199
+ # }
200
+ # .message-buttons-bot, .message-buttons-user {
201
+ # right: 10px !important;
202
+ # left: auto !important;
203
+ # bottom: 2px !important;
204
+ # }
205
+ # .dark.message-bubble-border {
206
+ # border-color: #343140 !important;
207
+ # }
208
+ # .dark.user {
209
+ # background: #1e1c26 !important;
210
+ # }
211
+ # .dark.assistant.dark, .dark.pending.dark {
212
+ # background: #16141c !important;
213
+ # }
214
+ # """
215
+
216
+ # def get_messages_formatter_type(model_name):
217
+ # if "Llama" in model_name:
218
+ # return MessagesFormatterType.LLAMA_3
219
+ # elif "Mistral" in model_name:
220
+ # return MessagesFormatterType.MISTRAL
221
+ # else:
222
+ # raise ValueError(f"Unsupported model: {model_name}")
223
 
224
+ # @spaces.GPU(duration=120)
225
+ # def respond(
226
+ # message,
227
+ # history: list[tuple[str, str]],
228
+ # model,
229
+ # system_message,
230
+ # max_tokens,
231
+ # temperature,
232
+ # top_p,
233
+ # top_k,
234
+ # repeat_penalty,
235
+ # ):
236
+ # chat_template = get_messages_formatter_type(model)
237
+
238
+ # llm = Llama(
239
+ # model_path=f"models/{model}",
240
+ # flash_attn=True,
241
+ # n_gpu_layers=81,
242
+ # n_batch=1024,
243
+ # n_ctx=8192,
244
+ # )
245
+ # provider = LlamaCppPythonProvider(llm)
246
 
247
+ # agent = LlamaCppAgent(
248
+ # provider,
249
+ # system_prompt=f"{system_message}",
250
+ # predefined_messages_formatter_type=chat_template,
251
+ # debug_output=True
252
+ # )
253
 
254
+ # settings = provider.get_provider_default_settings()
255
+ # settings.temperature = temperature
256
+ # settings.top_k = top_k
257
+ # settings.top_p = top_p
258
+ # settings.max_tokens = max_tokens
259
+ # settings.repeat_penalty = repeat_penalty
260
+ # settings.stream = True
261
+
262
+ # messages = BasicChatHistory()
263
+
264
+ # for msn in history:
265
+ # user = {
266
+ # 'role': Roles.user,
267
+ # 'content': msn[0]
268
+ # }
269
+ # assistant = {
270
+ # 'role': Roles.assistant,
271
+ # 'content': msn[1]
272
+ # }
273
+ # messages.add_message(user)
274
+ # messages.add_message(assistant)
275
 
276
+ # stream = agent.get_chat_response(
277
+ # message,
278
+ # llm_sampling_settings=settings,
279
+ # chat_history=messages,
280
+ # returns_streaming_generator=True,
281
+ # print_output=False
282
+ # )
283
 
284
+ # outputs = ""
285
+ # for output in stream:
286
+ # outputs += output
287
+ # yield outputs
288
+
289
+ # PLACEHOLDER = """
290
+ # <div class="message-bubble-border" style="display:flex; max-width: 600px; border-radius: 6px; border-width: 1px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); backdrop-filter: blur(10px);">
291
+ # <figure style="margin: 0;">
292
+ # <img src="https://huggingface.co/spaces/pabloce/llama-cpp-agent/resolve/main/llama.jpg" alt="Logo" style="width: 100%; height: 100%; border-radius: 8px;">
293
+ # </figure>
294
+ # <div style="padding: .5rem 1.5rem;">
295
+ # <h2 style="text-align: left; font-size: 1.5rem; font-weight: 700; margin-bottom: 0.5rem;">llama-cpp-agent</h2>
296
+ # <p style="text-align: left; font-size: 16px; line-height: 1.5; margin-bottom: 15px;">The llama-cpp-agent framework simplifies interactions with Large Language Models (LLMs), providing an interface for chatting, executing function calls, generating structured output, performing retrieval augmented generation, and processing text using agentic chains with tools.</p>
297
+ # <div style="display: flex; justify-content: space-between; align-items: center;">
298
+ # <div style="display: flex; flex-flow: column; justify-content: space-between;">
299
+ # <span style="display: inline-flex; align-items: center; border-radius: 0.375rem; background-color: rgba(229, 70, 77, 0.1); padding: 0.1rem 0.75rem; font-size: 0.75rem; font-weight: 500; color: #f88181; margin-bottom: 2.5px;">
300
+ # Mistral 7B Instruct v0.3
301
+ # </span>
302
+ # <span style="display: inline-flex; align-items: center; border-radius: 0.375rem; background-color: rgba(79, 70, 229, 0.1); padding: 0.1rem 0.75rem; font-size: 0.75rem; font-weight: 500; color: #60a5fa; margin-top: 2.5px;">
303
+ # Meta Llama 3 70B Instruct
304
+ # </span>
305
+ # </div>
306
+ # <div style="display: flex; justify-content: flex-end; align-items: center;">
307
+ # <a href="https://discord.gg/sRMvWKrh" target="_blank" rel="noreferrer" style="padding: .5rem;">
308
+ # <svg width="24" height="24" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 5 30.67 23.25">
309
+ # <title>Discord</title>
310
+ # <path d="M26.0015 6.9529C24.0021 6.03845 21.8787 5.37198 19.6623 5C19.3833 5.48048 19.0733 6.13144 18.8563 6.64292C16.4989 6.30193 14.1585 6.30193 11.8336 6.64292C11.6166 6.13144 11.2911 5.48048 11.0276 5C8.79575 5.37198 6.67235 6.03845 4.6869 6.9529C0.672601 12.8736 -0.41235 18.6548 0.130124 24.3585C2.79599 26.2959 5.36889 27.4739 7.89682 28.2489C8.51679 27.4119 9.07477 26.5129 9.55525 25.5675C8.64079 25.2265 7.77283 24.808 6.93587 24.312C7.15286 24.1571 7.36986 23.9866 7.57135 23.8161C12.6241 26.1255 18.0969 26.1255 23.0876 23.8161C23.3046 23.9866 23.5061 24.1571 23.7231 24.312C22.8861 24.808 22.0182 25.2265 21.1037 25.5675C21.5842 26.5129 22.1422 27.4119 22.7621 28.2489C25.2885 27.4739 27.8769 26.2959 30.5288 24.3585C31.1952 17.7559 29.4733 12.0212 26.0015 6.9529ZM10.2527 20.8402C8.73376 20.8402 7.49382 19.4608 7.49382 17.7714C7.49382 16.082 8.70276 14.7025 10.2527 14.7025C11.7871 14.7025 13.0425 16.082 13.0115 17.7714C13.0115 19.4608 11.7871 20.8402 10.2527 20.8402ZM20.4373 20.8402C18.9183 20.8402 17.6768 19.4608 17.6768 17.7714C17.6768 16.082 18.8873 14.7025 20.4373 14.7025C21.9717 14.7025 23.2271 16.082 23.1961 17.7714C23.1961 19.4608 21.9872 20.8402 20.4373 20.8402Z"></path>
311
+ # </svg>
312
+ # </a>
313
+ # <a href="https://github.com/Maximilian-Winter/llama-cpp-agent" target="_blank" rel="noreferrer" style="padding: .5rem;">
314
+ # <svg width="24" height="24" fill="currentColor" viewBox="3 3 18 18">
315
+ # <title>GitHub</title>
316
+ # <path d="M12 3C7.0275 3 3 7.12937 3 12.2276C3 16.3109 5.57625 19.7597 9.15374 20.9824C9.60374 21.0631 9.77249 20.7863 9.77249 20.5441C9.77249 20.3249 9.76125 19.5982 9.76125 18.8254C7.5 19.2522 6.915 18.2602 6.735 17.7412C6.63375 17.4759 6.19499 16.6569 5.8125 16.4378C5.4975 16.2647 5.0475 15.838 5.80124 15.8264C6.51 15.8149 7.01625 16.4954 7.18499 16.7723C7.99499 18.1679 9.28875 17.7758 9.80625 17.5335C9.885 16.9337 10.1212 16.53 10.38 16.2993C8.3775 16.0687 6.285 15.2728 6.285 11.7432C6.285 10.7397 6.63375 9.9092 7.20749 9.26326C7.1175 9.03257 6.8025 8.08674 7.2975 6.81794C7.2975 6.81794 8.05125 6.57571 9.77249 7.76377C10.4925 7.55615 11.2575 7.45234 12.0225 7.45234C12.7875 7.45234 13.5525 7.55615 14.2725 7.76377C15.9937 6.56418 16.7475 6.81794 16.7475 6.81794C17.2424 8.08674 16.9275 9.03257 16.8375 9.26326C17.4113 9.9092 17.76 10.7281 17.76 11.7432C17.76 15.2843 15.6563 16.0687 13.6537 16.2993C13.98 16.5877 14.2613 17.1414 14.2613 18.0065C14.2613 19.2407 14.25 20.2326 14.25 20.5441C14.25 20.7863 14.4188 21.0746 14.8688 20.9824C16.6554 20.364 18.2079 19.1866 19.3078 17.6162C20.4077 16.0457 20.9995 14.1611 21 12.2276C21 7.12937 16.9725 3 12 3Z"></path>
317
+ # </svg>
318
+ # </a>
319
+ # </div>
320
+ # </div>
321
+ # </div>
322
+ # </div>
323
+ # """
324
+
325
+ # demo = gr.ChatInterface(
326
+ # respond,
327
+ # additional_inputs=[
328
+ # gr.Dropdown([
329
+ # 'Meta-Llama-3-70B-Instruct-Q3_K_M.gguf',
330
+ # 'Mistral-7B-Instruct-v0.3-f32.gguf'
331
+ # ],
332
+ # value="Meta-Llama-3-70B-Instruct-Q3_K_M.gguf",
333
+ # label="Model"
334
+ # ),
335
+ # gr.Textbox(value="You are a helpful assistant.", label="System message"),
336
+ # gr.Slider(minimum=1, maximum=4096, value=2048, step=1, label="Max tokens"),
337
+ # gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
338
+ # gr.Slider(
339
+ # minimum=0.1,
340
+ # maximum=1.0,
341
+ # value=0.95,
342
+ # step=0.05,
343
+ # label="Top-p",
344
+ # ),
345
+ # gr.Slider(
346
+ # minimum=0,
347
+ # maximum=100,
348
+ # value=40,
349
+ # step=1,
350
+ # label="Top-k",
351
+ # ),
352
+ # gr.Slider(
353
+ # minimum=0.0,
354
+ # maximum=2.0,
355
+ # value=1.1,
356
+ # step=0.1,
357
+ # label="Repetition penalty",
358
+ # ),
359
+ # ],
360
+ # theme=gr.themes.Soft(primary_hue="violet", secondary_hue="violet", neutral_hue="gray",font=[gr.themes.GoogleFont("Exo"), "ui-sans-serif", "system-ui", "sans-serif"]).set(
361
+ # body_background_fill_dark="#16141c",
362
+ # block_background_fill_dark="#16141c",
363
+ # block_border_width="1px",
364
+ # block_title_background_fill_dark="#1e1c26",
365
+ # input_background_fill_dark="#292733",
366
+ # button_secondary_background_fill_dark="#24212b",
367
+ # border_color_accent_dark="#343140",
368
+ # border_color_primary_dark="#343140",
369
+ # background_fill_secondary_dark="#16141c",
370
+ # color_accent_soft_dark="transparent",
371
+ # code_background_fill_dark="#292733",
372
+ # ),
373
+ # css=css,
374
+ # retry_btn="Retry",
375
+ # undo_btn="Undo",
376
+ # clear_btn="Clear",
377
+ # submit_btn="Send",
378
+ # description="Llama-cpp-agent: Chat multi llm selection",
379
+ # chatbot=gr.Chatbot(
380
+ # scale=1,
381
+ # placeholder=PLACEHOLDER,
382
+ # likeable=False,
383
+ # show_copy_button=True
384
+ # )
385
+ # )
386
 
387
+ # if __name__ == "__main__":
388
+ # demo.launch()