srijaydeshpande commited on
Commit
6740fa2
·
1 Parent(s): 60cef4c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +359 -358
app.py CHANGED
@@ -30,185 +30,186 @@ hf_hub_download(
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('Control 0.5 -----------------------------------')
87
-
88
- # # model_id = "models/Meta-Llama-3-70B-Instruct-Q3_K_M.gguf"
89
- # # # model = Llama(model_path=model_id, n_ctx=2048, n_threads=8, n_gpu_layers=-1, n_batch=128)
90
- # # model = Llama(
91
- # # model_path=model_id,
92
- # # flash_attn=True,
93
- # # n_gpu_layers=81,
94
- # # n_batch=1024,
95
- # # n_ctx=8192,
96
- # # )
97
-
98
- # chat_template = MessagesFormatterType.LLAMA_3
99
-
100
- # print('Control 1-----------------------------------')
101
 
102
- # llm = Llama(
103
- # model_path="models/Meta-Llama-3-70B-Instruct-Q3_K_M.gguf",
104
- # flash_attn=True,
105
- # n_gpu_layers=81,
106
- # n_batch=1024,
107
- # n_ctx=8192,
108
- # )
109
- # print('Control 2-----------------------------------')
110
 
111
- # provider = LlamaCppPythonProvider(llm)
112
- # print('Control 3-----------------------------------')
113
 
114
- # agent = LlamaCppAgent(
115
- # provider,
116
- # system_prompt="You are a helpful assistant.",
117
- # predefined_messages_formatter_type=chat_template
118
- # )
119
- # print('Control 4-----------------------------------')
 
120
 
121
- # settings = provider.get_provider_default_settings()
122
- # settings.temperature = 0.7
123
- # settings.top_k = 40
124
- # settings.top_p = 0.95
125
- # settings.max_tokens = 2048
126
- # settings.repeat_penalty = 1.1
127
- # settings.stream = True
128
 
129
- # messages = BasicChatHistory()
130
 
131
- # stream = agent.get_chat_response(
132
- # prompt + ' : ' + pdftext,
133
- # llm_sampling_settings=settings,
134
- # returns_streaming_generator=True,
135
- # print_output=False
136
- # )
137
- # print('Control 5-----------------------------------')
138
- # outputs = ""
139
- # for output in stream:
140
- # outputs += output
141
- # yield outputs
142
 
143
- # # output = model.create_chat_completion(
144
- # # messages=[
145
- # # {"role": "assistant", "content": prompt},
146
- # # {
147
- # # "role": "user",
148
- # # "content": pdftext
149
- # # }
150
- # # ],
151
- # # max_tokens=maxtokens,
152
- # # temperature=temperature
153
- # # )
154
- # # output = output['choices'][0]['message']['content']
155
-
156
- # # 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]"
157
- # # output = model.create_chat_completion(
158
- # # messages=[
159
- # # {"role": "assistant", "content": prompt},
160
- # # {
161
- # # "role": "user",
162
- # # "content": output
163
- # # }
164
- # # ],
165
- # # max_tokens=maxtokens,
166
- # # temperature=temperature
167
- # # )
168
- # # output = output['choices'][0]['message']['content']
169
-
170
- # # print(prompt)
171
- # # print(output)
172
- # # print('-------------------------------------------------------')
173
-
174
- # # return outputs
175
 
176
- # @spaces.GPU(duration=120)
177
- # def pdf_to_text(files, maxtokens=2048, temperature=0, top_probability=0.95):
178
- # print('Control 0-----------------------------------')
179
- # files=[files]#remove later
180
- # for file in files:
181
- # file_name = os.path.basename(file)
182
- # file_name_splt = file_name.split('.')
183
- # # print('File name is ', file_name)
184
- # if (len(file_name_splt) > 1 and file_name_splt[1] == 'pdf'):
185
- # page2content = process_document(file, page_ids=[0])
186
- # pdftext = page2content[1]
187
- # print(pdftext)
188
- # # pdftext = file # remove later
189
- # if (pdftext): #shift this if block to right later
190
- # anonymized_text = deidentify_doc(pdftext, maxtokens, temperature, top_probability)
191
- # return anonymized_text
192
-
193
-
194
- # css = ".gradio-container {background: 'logo.png'}"
195
- # temp_slider = gr.Slider(minimum=0, maximum=2, value=0.9, label="Temperature Value")
196
- # prob_slider = gr.Slider(minimum=0, maximum=1, value=0.95, label="Max Probability Value")
197
- # max_tokens = gr.Number(value=600, label="Max Tokens")
198
- # input_folder = gr.File(file_count='multiple')
199
- # input_folder_text = gr.Textbox(label='Enter output folder path')
200
- # output_text = gr.Textbox()
201
- # output_path_component = gr.File(label="Select Output Path")
202
- # iface = gr.Interface(
203
- # fn=pdf_to_text,
204
- # inputs='file',
205
- # # inputs=["textbox", input_folder_text, "textbox", max_tokens, temp_slider, prob_slider],
206
- # outputs=output_text,
207
- # title='COBIx Endoscopy Report De-Identification',
208
- # description="This application assists to remove personal information from the uploaded clinical report",
209
- # theme=gr.themes.Soft(),
210
- # )
211
- # iface.launch()
212
 
213
  # import spaces
214
  # import json
@@ -232,201 +233,201 @@ hf_hub_download(
232
  # # local_dir = "./models"
233
  # # )
234
 
235
- css = """
236
- .message-row {
237
- justify-content: space-evenly !important;
238
- }
239
- .message-bubble-border {
240
- border-radius: 6px !important;
241
- }
242
- .message-buttons-bot, .message-buttons-user {
243
- right: 10px !important;
244
- left: auto !important;
245
- bottom: 2px !important;
246
- }
247
- .dark.message-bubble-border {
248
- border-color: #343140 !important;
249
- }
250
- .dark.user {
251
- background: #1e1c26 !important;
252
- }
253
- .dark.assistant.dark, .dark.pending.dark {
254
- background: #16141c !important;
255
- }
256
- """
257
-
258
- def get_messages_formatter_type(model_name):
259
- if "Llama" in model_name:
260
- return MessagesFormatterType.LLAMA_3
261
- elif "Mistral" in model_name:
262
- return MessagesFormatterType.MISTRAL
263
- else:
264
- raise ValueError(f"Unsupported model: {model_name}")
265
 
266
- @spaces.GPU(duration=120)
267
- def respond(
268
- message,
269
- history: list[tuple[str, str]],
270
- model,
271
- system_message,
272
- max_tokens,
273
- temperature,
274
- top_p,
275
- top_k,
276
- repeat_penalty,
277
- ):
278
- chat_template = get_messages_formatter_type(model)
279
 
280
- llm = Llama(
281
- model_path=f"models/{model}",
282
- flash_attn=True,
283
- n_gpu_layers=81,
284
- n_batch=1024,
285
- n_ctx=8192,
286
- )
287
- provider = LlamaCppPythonProvider(llm)
288
 
289
- agent = LlamaCppAgent(
290
- provider,
291
- system_prompt=f"{system_message}",
292
- predefined_messages_formatter_type=chat_template,
293
- debug_output=True
294
- )
295
 
296
- settings = provider.get_provider_default_settings()
297
- settings.temperature = temperature
298
- settings.top_k = top_k
299
- settings.top_p = top_p
300
- settings.max_tokens = max_tokens
301
- settings.repeat_penalty = repeat_penalty
302
- settings.stream = True
303
 
304
- messages = BasicChatHistory()
305
 
306
- print('history is ------------------ ', history)
307
 
308
- for msn in history:
309
- user = {
310
- 'role': Roles.user,
311
- 'content': msn[0]
312
- }
313
- assistant = {
314
- 'role': Roles.assistant,
315
- 'content': msn[1]
316
- }
317
- messages.add_message(user)
318
- messages.add_message(assistant)
319
 
320
- stream = agent.get_chat_response(
321
- message,
322
- llm_sampling_settings=settings,
323
- chat_history=messages,
324
- returns_streaming_generator=True,
325
- print_output=False
326
- )
327
 
328
- outputs = ""
329
- for output in stream:
330
- outputs += output
331
- yield outputs
332
 
333
- PLACEHOLDER = """
334
- <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);">
335
- <figure style="margin: 0;">
336
- <img src="https://huggingface.co/spaces/pabloce/llama-cpp-agent/resolve/main/llama.jpg" alt="Logo" style="width: 100%; height: 100%; border-radius: 8px;">
337
- </figure>
338
- <div style="padding: .5rem 1.5rem;">
339
- <h2 style="text-align: left; font-size: 1.5rem; font-weight: 700; margin-bottom: 0.5rem;">llama-cpp-agent</h2>
340
- <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>
341
- <div style="display: flex; justify-content: space-between; align-items: center;">
342
- <div style="display: flex; flex-flow: column; justify-content: space-between;">
343
- <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;">
344
- Mistral 7B Instruct v0.3
345
- </span>
346
- <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;">
347
- Meta Llama 3 70B Instruct
348
- </span>
349
- </div>
350
- <div style="display: flex; justify-content: flex-end; align-items: center;">
351
- <a href="https://discord.gg/sRMvWKrh" target="_blank" rel="noreferrer" style="padding: .5rem;">
352
- <svg width="24" height="24" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 5 30.67 23.25">
353
- <title>Discord</title>
354
- <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>
355
- </svg>
356
- </a>
357
- <a href="https://github.com/Maximilian-Winter/llama-cpp-agent" target="_blank" rel="noreferrer" style="padding: .5rem;">
358
- <svg width="24" height="24" fill="currentColor" viewBox="3 3 18 18">
359
- <title>GitHub</title>
360
- <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>
361
- </svg>
362
- </a>
363
- </div>
364
- </div>
365
- </div>
366
- </div>
367
- """
368
-
369
- demo = gr.ChatInterface(
370
- respond,
371
- additional_inputs=[
372
- gr.Dropdown([
373
- 'Meta-Llama-3-70B-Instruct-Q3_K_M.gguf',
374
- 'Mistral-7B-Instruct-v0.3-f32.gguf'
375
- ],
376
- value="Meta-Llama-3-70B-Instruct-Q3_K_M.gguf",
377
- label="Model"
378
- ),
379
- gr.Textbox(value="You are a helpful assistant.", label="System message"),
380
- gr.Slider(minimum=1, maximum=4096, value=2048, step=1, label="Max tokens"),
381
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
382
- gr.Slider(
383
- minimum=0.1,
384
- maximum=1.0,
385
- value=0.95,
386
- step=0.05,
387
- label="Top-p",
388
- ),
389
- gr.Slider(
390
- minimum=0,
391
- maximum=100,
392
- value=40,
393
- step=1,
394
- label="Top-k",
395
- ),
396
- gr.Slider(
397
- minimum=0.0,
398
- maximum=2.0,
399
- value=1.1,
400
- step=0.1,
401
- label="Repetition penalty",
402
- ),
403
- ],
404
- 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(
405
- body_background_fill_dark="#16141c",
406
- block_background_fill_dark="#16141c",
407
- block_border_width="1px",
408
- block_title_background_fill_dark="#1e1c26",
409
- input_background_fill_dark="#292733",
410
- button_secondary_background_fill_dark="#24212b",
411
- border_color_accent_dark="#343140",
412
- border_color_primary_dark="#343140",
413
- background_fill_secondary_dark="#16141c",
414
- color_accent_soft_dark="transparent",
415
- code_background_fill_dark="#292733",
416
- ),
417
- css=css,
418
- retry_btn="Retry",
419
- undo_btn="Undo",
420
- clear_btn="Clear",
421
- submit_btn="Send",
422
- description="Llama-cpp-agent: Chat multi llm selection",
423
- chatbot=gr.Chatbot(
424
- scale=1,
425
- placeholder=PLACEHOLDER,
426
- likeable=False,
427
- show_copy_button=True
428
- )
429
- )
430
 
431
- # if __name__ == "__main__":
432
- demo.launch()
 
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('Control 0.5 -----------------------------------')
87
+
88
+ # model_id = "models/Meta-Llama-3-70B-Instruct-Q3_K_M.gguf"
89
+ # # model = Llama(model_path=model_id, n_ctx=2048, n_threads=8, n_gpu_layers=-1, n_batch=128)
90
+ # model = Llama(
91
+ # model_path=model_id,
92
+ # flash_attn=True,
93
+ # n_gpu_layers=81,
94
+ # n_batch=1024,
95
+ # n_ctx=8192,
96
+ # )
97
+
98
+ chat_template = MessagesFormatterType.LLAMA_3
99
+
100
+ print('Control 1-----------------------------------')
101
 
102
+ llm = Llama(
103
+ model_path="models/Meta-Llama-3-70B-Instruct-Q3_K_M.gguf",
104
+ flash_attn=True,
105
+ n_gpu_layers=81,
106
+ n_batch=1024,
107
+ n_ctx=8192,
108
+ )
109
+ print('Control 2-----------------------------------')
110
 
111
+ provider = LlamaCppPythonProvider(llm)
112
+ print('Control 3-----------------------------------')
113
 
114
+ agent = LlamaCppAgent(
115
+ provider,
116
+ system_prompt="You are a helpful assistant.",
117
+ predefined_messages_formatter_type=chat_template,
118
+ debug_output=True
119
+ )
120
+ print('Control 4-----------------------------------')
121
 
122
+ settings = provider.get_provider_default_settings()
123
+ settings.temperature = 0.7
124
+ settings.top_k = 40
125
+ settings.top_p = 0.95
126
+ settings.max_tokens = 2048
127
+ settings.repeat_penalty = 1.1
128
+ settings.stream = True
129
 
130
+ messages = BasicChatHistory()
131
 
132
+ stream = agent.get_chat_response(
133
+ prompt + ' : ' + pdftext,
134
+ llm_sampling_settings=settings,
135
+ returns_streaming_generator=True,
136
+ print_output=False
137
+ )
138
+ print('Control 5-----------------------------------')
139
+ outputs = ""
140
+ for output in stream:
141
+ outputs += output
142
+ yield outputs
143
 
144
+ # output = model.create_chat_completion(
145
+ # messages=[
146
+ # {"role": "assistant", "content": prompt},
147
+ # {
148
+ # "role": "user",
149
+ # "content": pdftext
150
+ # }
151
+ # ],
152
+ # max_tokens=maxtokens,
153
+ # temperature=temperature
154
+ # )
155
+ # output = output['choices'][0]['message']['content']
156
+
157
+ # 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]"
158
+ # output = model.create_chat_completion(
159
+ # messages=[
160
+ # {"role": "assistant", "content": prompt},
161
+ # {
162
+ # "role": "user",
163
+ # "content": output
164
+ # }
165
+ # ],
166
+ # max_tokens=maxtokens,
167
+ # temperature=temperature
168
+ # )
169
+ # output = output['choices'][0]['message']['content']
170
+
171
+ # print(prompt)
172
+ # print(output)
173
+ # print('-------------------------------------------------------')
174
+
175
+ # return outputs
176
 
177
+ @spaces.GPU(duration=120)
178
+ def pdf_to_text(files, maxtokens=2048, temperature=0, top_probability=0.95):
179
+ print('Control 0-----------------------------------')
180
+ files=[files]#remove later
181
+ for file in files:
182
+ file_name = os.path.basename(file)
183
+ file_name_splt = file_name.split('.')
184
+ # print('File name is ', file_name)
185
+ if (len(file_name_splt) > 1 and file_name_splt[1] == 'pdf'):
186
+ page2content = process_document(file, page_ids=[0])
187
+ pdftext = page2content[1]
188
+ print(pdftext)
189
+ # pdftext = file # remove later
190
+ if (pdftext): #shift this if block to right later
191
+ anonymized_text = deidentify_doc(pdftext, maxtokens, temperature, top_probability)
192
+ return anonymized_text
193
+
194
+
195
+ css = ".gradio-container {background: 'logo.png'}"
196
+ temp_slider = gr.Slider(minimum=0, maximum=2, value=0.9, label="Temperature Value")
197
+ prob_slider = gr.Slider(minimum=0, maximum=1, value=0.95, label="Max Probability Value")
198
+ max_tokens = gr.Number(value=600, label="Max Tokens")
199
+ input_folder = gr.File(file_count='multiple')
200
+ input_folder_text = gr.Textbox(label='Enter output folder path')
201
+ output_text = gr.Textbox()
202
+ output_path_component = gr.File(label="Select Output Path")
203
+ iface = gr.Interface(
204
+ fn=pdf_to_text,
205
+ inputs='file',
206
+ # inputs=["textbox", input_folder_text, "textbox", max_tokens, temp_slider, prob_slider],
207
+ outputs=output_text,
208
+ title='COBIx Endoscopy Report De-Identification',
209
+ description="This application assists to remove personal information from the uploaded clinical report",
210
+ theme=gr.themes.Soft(),
211
+ )
212
+ iface.launch()
213
 
214
  # import spaces
215
  # import json
 
233
  # # local_dir = "./models"
234
  # # )
235
 
236
+ # css = """
237
+ # .message-row {
238
+ # justify-content: space-evenly !important;
239
+ # }
240
+ # .message-bubble-border {
241
+ # border-radius: 6px !important;
242
+ # }
243
+ # .message-buttons-bot, .message-buttons-user {
244
+ # right: 10px !important;
245
+ # left: auto !important;
246
+ # bottom: 2px !important;
247
+ # }
248
+ # .dark.message-bubble-border {
249
+ # border-color: #343140 !important;
250
+ # }
251
+ # .dark.user {
252
+ # background: #1e1c26 !important;
253
+ # }
254
+ # .dark.assistant.dark, .dark.pending.dark {
255
+ # background: #16141c !important;
256
+ # }
257
+ # """
258
+
259
+ # def get_messages_formatter_type(model_name):
260
+ # if "Llama" in model_name:
261
+ # return MessagesFormatterType.LLAMA_3
262
+ # elif "Mistral" in model_name:
263
+ # return MessagesFormatterType.MISTRAL
264
+ # else:
265
+ # raise ValueError(f"Unsupported model: {model_name}")
266
 
267
+ # @spaces.GPU(duration=120)
268
+ # def respond(
269
+ # message,
270
+ # history: list[tuple[str, str]],
271
+ # model,
272
+ # system_message,
273
+ # max_tokens,
274
+ # temperature,
275
+ # top_p,
276
+ # top_k,
277
+ # repeat_penalty,
278
+ # ):
279
+ # chat_template = get_messages_formatter_type(model)
280
 
281
+ # llm = Llama(
282
+ # model_path=f"models/{model}",
283
+ # flash_attn=True,
284
+ # n_gpu_layers=81,
285
+ # n_batch=1024,
286
+ # n_ctx=8192,
287
+ # )
288
+ # provider = LlamaCppPythonProvider(llm)
289
 
290
+ # agent = LlamaCppAgent(
291
+ # provider,
292
+ # system_prompt=f"{system_message}",
293
+ # predefined_messages_formatter_type=chat_template,
294
+ # debug_output=True
295
+ # )
296
 
297
+ # settings = provider.get_provider_default_settings()
298
+ # settings.temperature = temperature
299
+ # settings.top_k = top_k
300
+ # settings.top_p = top_p
301
+ # settings.max_tokens = max_tokens
302
+ # settings.repeat_penalty = repeat_penalty
303
+ # settings.stream = True
304
 
305
+ # messages = BasicChatHistory()
306
 
307
+ # print('history is ------------------ ', history)
308
 
309
+ # for msn in history:
310
+ # user = {
311
+ # 'role': Roles.user,
312
+ # 'content': msn[0]
313
+ # }
314
+ # assistant = {
315
+ # 'role': Roles.assistant,
316
+ # 'content': msn[1]
317
+ # }
318
+ # messages.add_message(user)
319
+ # messages.add_message(assistant)
320
 
321
+ # stream = agent.get_chat_response(
322
+ # message,
323
+ # llm_sampling_settings=settings,
324
+ # chat_history=messages,
325
+ # returns_streaming_generator=True,
326
+ # print_output=False
327
+ # )
328
 
329
+ # outputs = ""
330
+ # for output in stream:
331
+ # outputs += output
332
+ # yield outputs
333
 
334
+ # PLACEHOLDER = """
335
+ # <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);">
336
+ # <figure style="margin: 0;">
337
+ # <img src="https://huggingface.co/spaces/pabloce/llama-cpp-agent/resolve/main/llama.jpg" alt="Logo" style="width: 100%; height: 100%; border-radius: 8px;">
338
+ # </figure>
339
+ # <div style="padding: .5rem 1.5rem;">
340
+ # <h2 style="text-align: left; font-size: 1.5rem; font-weight: 700; margin-bottom: 0.5rem;">llama-cpp-agent</h2>
341
+ # <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>
342
+ # <div style="display: flex; justify-content: space-between; align-items: center;">
343
+ # <div style="display: flex; flex-flow: column; justify-content: space-between;">
344
+ # <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;">
345
+ # Mistral 7B Instruct v0.3
346
+ # </span>
347
+ # <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;">
348
+ # Meta Llama 3 70B Instruct
349
+ # </span>
350
+ # </div>
351
+ # <div style="display: flex; justify-content: flex-end; align-items: center;">
352
+ # <a href="https://discord.gg/sRMvWKrh" target="_blank" rel="noreferrer" style="padding: .5rem;">
353
+ # <svg width="24" height="24" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 5 30.67 23.25">
354
+ # <title>Discord</title>
355
+ # <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>
356
+ # </svg>
357
+ # </a>
358
+ # <a href="https://github.com/Maximilian-Winter/llama-cpp-agent" target="_blank" rel="noreferrer" style="padding: .5rem;">
359
+ # <svg width="24" height="24" fill="currentColor" viewBox="3 3 18 18">
360
+ # <title>GitHub</title>
361
+ # <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>
362
+ # </svg>
363
+ # </a>
364
+ # </div>
365
+ # </div>
366
+ # </div>
367
+ # </div>
368
+ # """
369
+
370
+ # demo = gr.ChatInterface(
371
+ # respond,
372
+ # additional_inputs=[
373
+ # gr.Dropdown([
374
+ # 'Meta-Llama-3-70B-Instruct-Q3_K_M.gguf',
375
+ # 'Mistral-7B-Instruct-v0.3-f32.gguf'
376
+ # ],
377
+ # value="Meta-Llama-3-70B-Instruct-Q3_K_M.gguf",
378
+ # label="Model"
379
+ # ),
380
+ # gr.Textbox(value="You are a helpful assistant.", label="System message"),
381
+ # gr.Slider(minimum=1, maximum=4096, value=2048, step=1, label="Max tokens"),
382
+ # gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
383
+ # gr.Slider(
384
+ # minimum=0.1,
385
+ # maximum=1.0,
386
+ # value=0.95,
387
+ # step=0.05,
388
+ # label="Top-p",
389
+ # ),
390
+ # gr.Slider(
391
+ # minimum=0,
392
+ # maximum=100,
393
+ # value=40,
394
+ # step=1,
395
+ # label="Top-k",
396
+ # ),
397
+ # gr.Slider(
398
+ # minimum=0.0,
399
+ # maximum=2.0,
400
+ # value=1.1,
401
+ # step=0.1,
402
+ # label="Repetition penalty",
403
+ # ),
404
+ # ],
405
+ # 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(
406
+ # body_background_fill_dark="#16141c",
407
+ # block_background_fill_dark="#16141c",
408
+ # block_border_width="1px",
409
+ # block_title_background_fill_dark="#1e1c26",
410
+ # input_background_fill_dark="#292733",
411
+ # button_secondary_background_fill_dark="#24212b",
412
+ # border_color_accent_dark="#343140",
413
+ # border_color_primary_dark="#343140",
414
+ # background_fill_secondary_dark="#16141c",
415
+ # color_accent_soft_dark="transparent",
416
+ # code_background_fill_dark="#292733",
417
+ # ),
418
+ # css=css,
419
+ # retry_btn="Retry",
420
+ # undo_btn="Undo",
421
+ # clear_btn="Clear",
422
+ # submit_btn="Send",
423
+ # description="Llama-cpp-agent: Chat multi llm selection",
424
+ # chatbot=gr.Chatbot(
425
+ # scale=1,
426
+ # placeholder=PLACEHOLDER,
427
+ # likeable=False,
428
+ # show_copy_button=True
429
+ # )
430
+ # )
431
 
432
+ # # if __name__ == "__main__":
433
+ # demo.launch()