Spaces:
Sleeping
Sleeping
File size: 17,748 Bytes
c68892d f59f99a c68892d f59f99a c68892d f59f99a 19e7e1f aa98be2 19e7e1f 20f48e5 19e7e1f f59f99a 19e7e1f 20f48e5 19e7e1f f59f99a 19e7e1f f59f99a 19e7e1f f59f99a 19e7e1f aa98be2 19e7e1f b26fc16 19e7e1f c68892d 009b11d c68892d 19e7e1f c68892d 19e7e1f c68892d 19e7e1f c68892d 19e7e1f c68892d 19e7e1f c68892d 19e7e1f c68892d 19e7e1f c68892d 19e7e1f 25d8974 19e7e1f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 |
from pdfminer.high_level import extract_pages
from pdfminer.layout import LTTextContainer
from tqdm import tqdm
import re
import gradio as gr
import os
import accelerate
import spaces
import subprocess
from huggingface_hub import hf_hub_download
from llama_cpp import Llama
from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
from llama_cpp_agent.providers import LlamaCppPythonProvider
from llama_cpp_agent.chat_history import BasicChatHistory
from llama_cpp_agent.chat_history.messages import Roles
# subprocess.run('pip install llama-cpp-python==0.2.75 --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu124', shell=True)
# subprocess.run('pip install llama-cpp-agent==0.2.10', shell=True)
# hf_hub_download(
# repo_id="QuantFactory/Meta-Llama-3-8B-Instruct-GGUF",
# filename="Meta-Llama-3-8B-Instruct.Q8_0.gguf",
# local_dir = "./models"
# )
hf_hub_download(
repo_id="bartowski/Meta-Llama-3-70B-Instruct-GGUF",
filename="Meta-Llama-3-70B-Instruct-Q3_K_M.gguf",
local_dir = "./models"
)
# def process_document(pdf_path, page_ids=None):
# extracted_pages = extract_pages(pdf_path, page_numbers=page_ids)
# page2content = {}
# for extracted_page in tqdm(extracted_pages):
# page_id = extracted_page.pageid
# content = process_page(extracted_page)
# page2content[page_id] = content
# return page2content
# def process_page(extracted_page):
# content = []
# elements = [element for element in extracted_page._objs]
# elements.sort(key=lambda a: a.y1, reverse=True)
# for i, element in enumerate(elements):
# if isinstance(element, LTTextContainer):
# line_text = extract_text_and_normalize(element)
# content.append(line_text)
# content = re.sub('\n+', ' ', ''.join(content))
# return content
# def extract_text_and_normalize(element):
# # Extract text from line and split it with new lines
# line_texts = element.get_text().split('\n')
# norm_text = ''
# for line_text in line_texts:
# line_text = line_text.strip()
# if not line_text:
# line_text = '\n'
# else:
# line_text = re.sub('\s+', ' ', line_text)
# if not re.search('[\w\d\,\-]', line_text[-1]):
# line_text += '\n'
# else:
# line_text += ' '
# norm_text += line_text
# return norm_text
# def txt_to_html(text):
# html_content = "<html><body>"
# for line in text.split('\n'):
# html_content += "<p>{}</p>".format(line.strip())
# html_content += "</body></html>"
# return html_content
# @spaces.GPU(duration=60)
# def deidentify_doc(pdftext, maxtokens, temperature, top_probability):
# # 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]"
# prompt = "Perform the following actions on given report: 1. Replace any person names and person date of birth and person age and person gender with term [redacted] 2. Replace any person addresses with term [redacted] 3. Replace any person age with term [redacted] 4. DO NOT REPLACE ANY MEDICAL MEASUREMENTS 5. Replace only the CALENDAR DATES of format 'day/month/year' with term [redacted]"
# # model_id = "models/Meta-Llama-3-70B-Instruct-Q3_K_M.gguf"
# # # model = Llama(model_path=model_id, n_ctx=2048, n_threads=8, n_gpu_layers=-1, n_batch=128)
# # model = Llama(
# # model_path=model_id,
# # flash_attn=True,
# # n_gpu_layers=81,
# # n_batch=1024,
# # n_ctx=8192,
# # )
# chat_template = MessagesFormatterType.LLAMA_3
# llm = Llama(
# model_path="models/Meta-Llama-3-70B-Instruct-Q3_K_M.gguf",
# flash_attn=True,
# n_gpu_layers=81,
# n_batch=1024,
# n_ctx=8192,
# )
# provider = LlamaCppPythonProvider(llm)
# agent = LlamaCppAgent(
# provider,
# system_prompt="You are a helpful assistant.",
# predefined_messages_formatter_type=chat_template,
# debug_output=True
# )
# settings = provider.get_provider_default_settings()
# settings.temperature = 0.7
# settings.top_k = 40
# settings.top_p = 0.95
# settings.max_tokens = 2048
# settings.repeat_penalty = 1.1
# settings.stream = True
# messages = BasicChatHistory()
# stream = agent.get_chat_response(
# prompt + ' : ' + pdftext,
# llm_sampling_settings=settings,
# chat_history=messages,
# returns_streaming_generator=True,
# print_output=False
# )
# outputs = ""
# for output in stream:
# outputs += output
# return outputs
# # output = model.create_chat_completion(
# # messages=[
# # {"role": "assistant", "content": prompt},
# # {
# # "role": "user",
# # "content": pdftext
# # }
# # ],
# # max_tokens=maxtokens,
# # temperature=temperature
# # )
# # output = output['choices'][0]['message']['content']
# # 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]"
# # output = model.create_chat_completion(
# # messages=[
# # {"role": "assistant", "content": prompt},
# # {
# # "role": "user",
# # "content": output
# # }
# # ],
# # max_tokens=maxtokens,
# # temperature=temperature
# # )
# # output = output['choices'][0]['message']['content']
# # print(prompt)
# # print(output)
# # print('-------------------------------------------------------')
# # return outputs
# def pdf_to_text(files, maxtokens=2048, temperature=0, top_probability=0.95):
# print('Control 0-----------------------------------')
# files=[files]#remove later
# for file in files:
# file_name = os.path.basename(file)
# file_name_splt = file_name.split('.')
# # print('File name is ', file_name)
# if (len(file_name_splt) > 1 and file_name_splt[1] == 'pdf'):
# page2content = process_document(file, page_ids=[0])
# pdftext = page2content[1]
# print(pdftext)
# # pdftext = file # remove later
# if (pdftext): #shift this if block to right later
# anonymized_text = deidentify_doc(pdftext, maxtokens, temperature, top_probability)
# return anonymized_text
# css = ".gradio-container {background: 'logo.png'}"
# temp_slider = gr.Slider(minimum=0, maximum=2, value=0.9, label="Temperature Value")
# prob_slider = gr.Slider(minimum=0, maximum=1, value=0.95, label="Max Probability Value")
# max_tokens = gr.Number(value=600, label="Max Tokens")
# input_folder = gr.File(file_count='multiple')
# input_folder_text = gr.Textbox(label='Enter output folder path')
# output_text = gr.Textbox()
# output_path_component = gr.File(label="Select Output Path")
# iface = gr.Interface(
# fn=pdf_to_text,
# inputs='file',
# # inputs=["textbox", input_folder_text, "textbox", max_tokens, temp_slider, prob_slider],
# outputs=output_text,
# title='COBIx Endoscopy Report De-Identification',
# description="This application assists to remove personal information from the uploaded clinical report",
# theme=gr.themes.Soft(),
# )
# iface.launch()
# import spaces
# import json
# import subprocess
# from llama_cpp import Llama
# from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
# from llama_cpp_agent.providers import LlamaCppPythonProvider
# from llama_cpp_agent.chat_history import BasicChatHistory
# from llama_cpp_agent.chat_history.messages import Roles
# import gradio as gr
# from huggingface_hub import hf_hub_download
# hf_hub_download(
# repo_id="bartowski/Meta-Llama-3-70B-Instruct-GGUF",
# filename="Meta-Llama-3-70B-Instruct-Q3_K_M.gguf",
# local_dir = "./models"
# )
# # hf_hub_download(
# # repo_id="bartowski/Mistral-7B-Instruct-v0.3-GGUF",
# # filename="Mistral-7B-Instruct-v0.3-f32.gguf",
# # local_dir = "./models"
# # )
css = """
.message-row {
justify-content: space-evenly !important;
}
.message-bubble-border {
border-radius: 6px !important;
}
.message-buttons-bot, .message-buttons-user {
right: 10px !important;
left: auto !important;
bottom: 2px !important;
}
.dark.message-bubble-border {
border-color: #343140 !important;
}
.dark.user {
background: #1e1c26 !important;
}
.dark.assistant.dark, .dark.pending.dark {
background: #16141c !important;
}
"""
def get_messages_formatter_type(model_name):
if "Llama" in model_name:
return MessagesFormatterType.LLAMA_3
elif "Mistral" in model_name:
return MessagesFormatterType.MISTRAL
else:
raise ValueError(f"Unsupported model: {model_name}")
@spaces.GPU(duration=60)
def respond(
message,
history: list[tuple[str, str]],
model,
system_message,
max_tokens,
temperature,
top_p,
top_k,
repeat_penalty,
):
chat_template = get_messages_formatter_type(model)
llm = Llama(
model_path=f"models/{model}",
flash_attn=True,
n_gpu_layers=81,
n_batch=1024,
n_ctx=8192,
)
provider = LlamaCppPythonProvider(llm)
agent = LlamaCppAgent(
provider,
system_prompt=f"{system_message}",
predefined_messages_formatter_type=chat_template,
debug_output=True
)
settings = provider.get_provider_default_settings()
settings.temperature = temperature
settings.top_k = top_k
settings.top_p = top_p
settings.max_tokens = max_tokens
settings.repeat_penalty = repeat_penalty
settings.stream = True
messages = BasicChatHistory()
for msn in history:
user = {
'role': Roles.user,
'content': msn[0]
}
assistant = {
'role': Roles.assistant,
'content': msn[1]
}
messages.add_message(user)
messages.add_message(assistant)
stream = agent.get_chat_response(
message,
llm_sampling_settings=settings,
chat_history=messages,
returns_streaming_generator=True,
print_output=False
)
outputs = ""
for output in stream:
outputs += output
yield outputs
PLACEHOLDER = """
<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);">
<figure style="margin: 0;">
<img src="https://huggingface.co/spaces/pabloce/llama-cpp-agent/resolve/main/llama.jpg" alt="Logo" style="width: 100%; height: 100%; border-radius: 8px;">
</figure>
<div style="padding: .5rem 1.5rem;">
<h2 style="text-align: left; font-size: 1.5rem; font-weight: 700; margin-bottom: 0.5rem;">llama-cpp-agent</h2>
<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>
<div style="display: flex; justify-content: space-between; align-items: center;">
<div style="display: flex; flex-flow: column; justify-content: space-between;">
<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;">
Mistral 7B Instruct v0.3
</span>
<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;">
Meta Llama 3 70B Instruct
</span>
</div>
<div style="display: flex; justify-content: flex-end; align-items: center;">
<a href="https://discord.gg/sRMvWKrh" target="_blank" rel="noreferrer" style="padding: .5rem;">
<svg width="24" height="24" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 5 30.67 23.25">
<title>Discord</title>
<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>
</svg>
</a>
<a href="https://github.com/Maximilian-Winter/llama-cpp-agent" target="_blank" rel="noreferrer" style="padding: .5rem;">
<svg width="24" height="24" fill="currentColor" viewBox="3 3 18 18">
<title>GitHub</title>
<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>
</svg>
</a>
</div>
</div>
</div>
</div>
"""
demo = gr.ChatInterface(
respond,
additional_inputs=[
gr.Dropdown([
'Meta-Llama-3-70B-Instruct-Q3_K_M.gguf',
'Mistral-7B-Instruct-v0.3-f32.gguf'
],
value="Meta-Llama-3-70B-Instruct-Q3_K_M.gguf",
label="Model"
),
gr.Textbox(value="You are a helpful assistant.", label="System message"),
gr.Slider(minimum=1, maximum=4096, value=2048, step=1, label="Max tokens"),
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
gr.Slider(
minimum=0.1,
maximum=1.0,
value=0.95,
step=0.05,
label="Top-p",
),
gr.Slider(
minimum=0,
maximum=100,
value=40,
step=1,
label="Top-k",
),
gr.Slider(
minimum=0.0,
maximum=2.0,
value=1.1,
step=0.1,
label="Repetition penalty",
),
],
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(
body_background_fill_dark="#16141c",
block_background_fill_dark="#16141c",
block_border_width="1px",
block_title_background_fill_dark="#1e1c26",
input_background_fill_dark="#292733",
button_secondary_background_fill_dark="#24212b",
border_color_accent_dark="#343140",
border_color_primary_dark="#343140",
background_fill_secondary_dark="#16141c",
color_accent_soft_dark="transparent",
code_background_fill_dark="#292733",
),
css=css,
retry_btn="Retry",
undo_btn="Undo",
clear_btn="Clear",
submit_btn="Send",
description="Llama-cpp-agent: Chat multi llm selection",
chatbot=gr.Chatbot(
scale=1,
placeholder=PLACEHOLDER,
likeable=False,
show_copy_button=True
)
)
# if __name__ == "__main__":
demo.launch() |