ai_dad_jokes / app_dialogue.py
VictorSanh's picture
longer seq length
bb45364
raw
history blame contribute delete
No virus
29.1 kB
import ast
import copy
import glob
import hashlib
import logging
import os
import re
from pathlib import Path
from typing import List, Optional, Tuple
from urllib.parse import urlparse
import gradio as gr
import PIL
from gradio import processing_utils
from gradio_client.client import DEFAULT_TEMP_DIR
from text_generation import Client
from transformers import AutoProcessor
MODELS = [
# "HuggingFaceM4/idefics-9b-instruct",
"HuggingFaceM4/idefics-80b-instruct",
]
API_PATHS = {
"HuggingFaceM4/idefics-9b-instruct": (
"https://api-inference.huggingface.co/models/HuggingFaceM4/idefics-9b-instruct"
),
"HuggingFaceM4/idefics-80b-instruct": (
"https://api-inference.huggingface.co/models/HuggingFaceM4/idefics-80b-instruct"
),
}
SYSTEM_PROMPT = [
"""The following is a conversation between a highly knowledgeable and intelligent visual AI assistant, called Assistant, and a human user, called User.
In the following interactions, User and Assistant will converse in natural language, and Assistant will answer in a sassy way.
Assistant's main purpose is to create funny meme texts from the images User provides.
Assistant should be funny, sassy, and impertinent, and sometimes Assistant roasts people.
Assistant should not be mean. It should not say toxic, homophobic, sexist, racist, things or any demeaning things that can make people uncomfortable.
Assistant was created by Hugging Face.
Here's a conversation example:""",
"""\nUser:""",
"https://ichef.bbci.co.uk/news/976/cpsprodpb/7727/production/_103330503_musk3.jpg",
"Write a meme for that image.<end_of_utterance>",
"""\nAssistant: When you're trying to quit smoking but the cravings are too strong.<end_of_utterance>""",
"\nUser:How about this image?",
"https://www.boredpanda.com/blog/wp-content/uploads/2017/01/image-copy-copy-587d0e7918b57-png__700.jpg",
"Write something funny about this image.<end_of_utterance>",
"""\nAssistant: Eggcellent service!<end_of_utterance>""",
"\nUser: Roast this person",
"https://i.pinimg.com/564x/98/34/4b/98344b2483bd7c8b71a5c0fed6fe20b6.jpg",
"<end_of_utterance>",
"""\nAssistant: Damn your handwritting is pretty awful. But I suppose it must be pretty hard to hold a pen, considering you are a hammerhead shark.<end_of_utterance>""",
]
BAN_TOKENS = ( # For documentation puporse. We are not using this list, it is hardcoded inside `idefics_causal_lm.py` inside TGI.
"<image>;<fake_token_around_image>"
)
EOS_STRINGS = ["<end_of_utterance>", "\nUser:"]
STOP_SUSPECT_LIST = []
GRADIO_LINK = "https://huggingfacem4-ai-dad-jokes.hf.space"
API_TOKEN = os.getenv("HF_AUTH_TOKEN")
IDEFICS_LOGO = "https://huggingface.co/spaces/HuggingFaceM4/idefics_playground/resolve/main/IDEFICS_logo.png"
PROCESSOR = AutoProcessor.from_pretrained(
"HuggingFaceM4/idefics-9b-instruct",
token=API_TOKEN,
)
BOT_AVATAR = "IDEFICS_logo.png"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
# Monkey patch adapted from gradio.components.image.Image - mostly to make the `save` step optional in `pil_to_temp_file`
def hash_bytes(bytes: bytes):
sha1 = hashlib.sha1()
sha1.update(bytes)
return sha1.hexdigest()
def pil_to_temp_file(img: PIL.Image.Image, dir: str = DEFAULT_TEMP_DIR, format: str = "png") -> str:
"""Save a PIL image into a temp file"""
bytes_data = processing_utils.encode_pil_to_bytes(img, format)
temp_dir = Path(dir) / hash_bytes(bytes_data)
temp_dir.mkdir(exist_ok=True, parents=True)
filename = str(temp_dir / f"image.{format}")
if not os.path.exists(filename):
img.save(filename, pnginfo=processing_utils.get_pil_metadata(img))
return filename
def add_file(file):
return file.name, gr.update(label='πŸ–ΌοΈ Uploaded!')
# This is a hack to make pre-computing the default examples work.
# During normal inference, we pass images as url to a local file using the method `gradio_link`
# which allows the tgi server to fetch the local image from the frontend server.
# however, we are building the space (and pre-computing is part of building the space), the frontend is not available
# and won't answer. So tgi server will try to fetch an image that is not available yet, which will result in a timeout error
# because tgi will never be able to return the generation.
# To bypass that, we pass instead the images URLs from the spaces repo.
all_images = glob.glob(f"{os.path.dirname(__file__)}/example_images/*")
DEFAULT_IMAGES_TMP_PATH_TO_URL = {}
for im_path in all_images:
H = gr.Image(im_path, visible=False, type="filepath")
tmp_filename = H.preprocess(H.value)
DEFAULT_IMAGES_TMP_PATH_TO_URL[tmp_filename] = f"https://huggingface.co/spaces/HuggingFaceM4/ai_dad_jokes/resolve/main/example_images/{os.path.basename(im_path)}"
# Utils to handle the image markdown display logic
def split_str_on_im_markdown(string: str) -> List[str]:
"""
Extract from a string (typically the user prompt string) the potential images from markdown
Examples:
- `User:![](https://favurl.com/chicken_on_money.png)Describe this image.` would become `["User:", "https://favurl.com/chicken_on_money.png", "Describe this image."]`
- `User:![](/file=/my_temp/chicken_on_money.png)Describe this image.` would become `["User:", "/my_temp/chicken_on_money.png", "Describe this image."]`
"""
IMAGES_PATTERN = re.compile(r"!\[[^\]]*\]\((.*?)\s*(\"(?:.*[^\"])\")?\s*\)")
parts = []
cursor = 0
for pattern in IMAGES_PATTERN.finditer(string):
start = pattern.start()
if start != cursor:
parts.append(string[cursor:start])
image_url = pattern.group(1)
if image_url.startswith("/file="):
image_url = image_url[6:] # Remove the 'file=' prefix
parts.append(image_url)
cursor = pattern.end()
if cursor != len(string):
parts.append(string[cursor:])
return parts
def is_image(string: str) -> bool:
"""
There are two ways for images: local image path or url.
"""
return is_url(string) or string.startswith(DEFAULT_TEMP_DIR)
def is_url(string: str) -> bool:
"""
Checks if the passed string contains a valid url and nothing else. e.g. if space is included it's immediately
invalidated the url
"""
if " " in string:
return False
result = urlparse(string)
return all([result.scheme, result.netloc])
def isolate_images_urls(prompt_list: List) -> List:
"""
Convert a full string prompt to the list format expected by the processor.
In particular, image urls (as delimited by <fake_token_around_image>) should be their own elements.
From:
```
[
"bonjour<fake_token_around_image><image:IMG_URL><fake_token_around_image>hello",
PIL.Image.Image,
"Aurevoir",
]
```
to:
```
[
"bonjour",
IMG_URL,
"hello",
PIL.Image.Image,
"Aurevoir",
]
```
"""
linearized_list = []
for prompt in prompt_list:
# Prompt can be either a string, or a PIL image
if isinstance(prompt, PIL.Image.Image):
linearized_list.append(prompt)
elif isinstance(prompt, str):
if "<fake_token_around_image>" not in prompt:
linearized_list.append(prompt)
else:
prompt_splitted = prompt.split("<fake_token_around_image>")
for ps in prompt_splitted:
if ps == "":
continue
if ps.startswith("<image:"):
linearized_list.append(ps[7:-1])
else:
linearized_list.append(ps)
else:
raise TypeError(
f"Unrecognized type for `prompt`. Got {type(type(prompt))}. Was expecting something in [`str`,"
" `PIL.Image.Image`]"
)
return linearized_list
def fetch_images(url_list: str) -> PIL.Image.Image:
"""Fetching images"""
return PROCESSOR.image_processor.fetch_images(url_list)
def handle_manual_images_in_user_prompt(user_prompt: str) -> List[str]:
"""
Handle the case of textually manually inputted images (i.e. the `<fake_token_around_image><image:IMG_URL><fake_token_around_image>`) in the user prompt
by fetching them, saving them locally and replacing the whole sub-sequence the image local path.
"""
if "<fake_token_around_image>" in user_prompt:
splitted_user_prompt = isolate_images_urls([user_prompt])
resulting_user_prompt = []
for u_p in splitted_user_prompt:
if is_url(u_p):
img = fetch_images([u_p])[0]
tmp_file = pil_to_temp_file(img)
resulting_user_prompt.append(tmp_file)
else:
resulting_user_prompt.append(u_p)
return resulting_user_prompt
else:
return [user_prompt]
def gradio_link(img_path: str) -> str:
url = f"{GRADIO_LINK}/file={img_path}"
return url
def prompt_list_to_markdown(prompt_list: List[str]) -> str:
"""
Convert a user prompt in the list format (i.e. elements are either a PIL image or a string) into
the markdown format that is used for the chatbot history and rendering.
"""
resulting_string = ""
for elem in prompt_list:
if is_image(elem):
if is_url(elem):
resulting_string += f"![]({elem})"
else:
resulting_string += f"![](/file={elem})"
else:
resulting_string += elem
return resulting_string
def prompt_list_to_tgi_input(prompt_list: List[str]) -> str:
"""
TGI expects a string that contains both text and images in the image markdown format (i.e. the `![]()` ).
The images links are parsed on TGI side
"""
result_string_input = ""
for elem in prompt_list:
if is_image(elem):
if is_url(elem):
result_string_input += f"![]({elem})"
else:
result_string_input += f"![]({gradio_link(img_path=elem)})"
else:
result_string_input += elem
return result_string_input
def remove_spaces_around_token(text: str) -> str:
pattern = r"\s*(<fake_token_around_image>)\s*"
replacement = r"\1"
result = re.sub(pattern, replacement, text)
return result
# Chatbot utils
def format_user_prompt_with_im_history_and_system_conditioning(
system_prompt: List[str], current_user_prompt_str: str, current_image: Optional[str], history: List[Tuple[str, str]]
) -> Tuple[List[str], List[str]]:
"""
Produces the resulting list that needs to go inside the processor.
It handles the potential image box input, the history and the system conditionning.
"""
# resulting_list = copy.deepcopy(SYSTEM_PROMPT)
resulting_list = system_prompt
# Format history
for turn in history:
user_utterance, assistant_utterance = turn
splitted_user_utterance = split_str_on_im_markdown(user_utterance)
optional_space = ""
if not is_image(splitted_user_utterance[0]):
optional_space = " "
resulting_list.append(f"\nUser:{optional_space}")
resulting_list.extend(splitted_user_utterance)
resulting_list.append(f"<end_of_utterance>\nAssistant: {assistant_utterance}")
# Format current input
current_user_prompt_str = remove_spaces_around_token(current_user_prompt_str)
if current_image is None:
if "![](" in current_user_prompt_str:
current_user_prompt_list = split_str_on_im_markdown(current_user_prompt_str)
else:
current_user_prompt_list = handle_manual_images_in_user_prompt(current_user_prompt_str)
optional_space = ""
if not is_image(current_user_prompt_list[0]):
# Check if the first element is an image (and more precisely a path to an image)
optional_space = " "
resulting_list.append(f"\nUser:{optional_space}")
resulting_list.extend(current_user_prompt_list)
resulting_list.append("<end_of_utterance>\nAssistant:")
else:
# Choosing to put the image first when the image is inputted through the UI, but this is an arbiratrary choice.
resulting_list.extend(["\nUser:", current_image, f"{current_user_prompt_str}<end_of_utterance>\nAssistant:"])
current_user_prompt_list = [current_user_prompt_str]
return resulting_list, current_user_prompt_list
# dope_callback = gr.CSVLogger()
# problematic_callback = gr.CSVLogger()
textbox = gr.Textbox(
placeholder="Upload an image and begin chatting with a message! Images can be added at each turn.",
show_label=False,
# value="Write something funny about that image.",
visible=True,
container=False,
label="Text input",
scale=8,
max_lines=5,
)
chatbot = gr.Chatbot(
elem_id="chatbot",
label="AI Dad Jokes",
visible=True,
height=750,
avatar_images=[None, BOT_AVATAR]
)
with gr.Blocks(title="AI Dad Jokes", theme=gr.themes.Base()) as demo:
gr.HTML("""<h1 align="center">AI Dad Jokes</h1>""")
with gr.Row(variant="panel"):
with gr.Column(scale=1):
gr.Image(IDEFICS_LOGO, elem_id="banner-image", show_label=False, show_download_button=False)
with gr.Column(scale=5):
gr.HTML("""
<p><strong>AI Dad Jokes</strong> is an AI system that writes humorous content inspired by images. Whether that's crafting memes, sharing light-hearted yet amiable jests, or playfully witty remarks, AI Dad Jokes assists you in creating delightful jokes!</p>
<p>AI Dad Jokes is powered by <a href="https://huggingface.co/blog/idefics">IDEFICS</a>, an open-access large visual language model developped by Hugging Face. Like GPT-4, the multimodal model accepts arbitrary sequences of image and text inputs and produces text outputs. IDEFICS can answer questions about images, describe visual content, create stories grounded in multiple images, etc.</p>
<p>⛔️ <strong>Intended uses and limitations:</strong> This demo is provided as research artifact to the community showcasing IDEFIC's capabilities. We detail misuses and out-of-scope uses <a href="https://huggingface.co/HuggingFaceM4/idefics-80b#misuse-and-out-of-scope-use">here</a>. In particular, the system should not be used to engage in harassment, abuse and bullying. The model can produce factually incorrect texts, hallucinate facts (with or without an image) and will struggle with small details in images. While the system will tend to refuse answering questionable user requests, it can produce problematic outputs (including racist, stereotypical, and disrespectful texts), in particular when prompted to do so.</p>
""")
with gr.Row(elem_id="model_selector_row"):
model_selector = gr.Dropdown(
choices=MODELS,
value="HuggingFaceM4/idefics-80b-instruct",
interactive=True,
show_label=False,
container=False,
label="Model",
visible=False,
)
with gr.Row():
with gr.Column():
imagebox = gr.Image(type="filepath", label="Image input", visible=True)
with gr.Group():
with gr.Row():
textbox.render()
submit_btn = gr.Button(value="▢️ Submit", visible=True)
with gr.Row():
clear_btn = gr.ClearButton([textbox, imagebox, chatbot], value="🧹 Clear")
regenerate_btn = gr.Button(value="πŸ”„ Regenerate", visible=True)
upload_btn = gr.UploadButton("πŸ“ Upload image", file_types=["image"],visible=False)
with gr.Accordion("Advanced settings", open=False, visible=True) as parameter_row:
system_prompt = gr.Textbox(
value=SYSTEM_PROMPT,
visible=False,
lines=20,
max_lines=50,
interactive=True,
)
max_new_tokens = gr.Slider(
minimum=8,
maximum=256,
value=128,
step=1,
interactive=True,
label="Maximum number of new tokens to generate",
)
repetition_penalty = gr.Slider(
minimum=0.0,
maximum=5.0,
value=1.2,
step=0.01,
interactive=True,
label="Repetition penalty",
info="1.0 is equivalent to no penalty",
)
decoding_strategy = gr.Radio(
[
"Greedy",
"Top P Sampling",
],
value="Top P Sampling",
label="Decoding strategy",
interactive=True,
info="Higher values is equivalent to sampling more low-probability tokens.",
)
temperature = gr.Slider(
minimum=0.0,
maximum=5.0,
value=0.6,
step=0.1,
interactive=True,
visible=True,
label="Sampling temperature",
info="Higher values will produce more diverse outputs.",
)
decoding_strategy.change(
fn=lambda selection: gr.Slider.update(
visible=(
selection in ["contrastive_sampling", "beam_sampling", "Top P Sampling", "sampling_top_k"]
)
),
inputs=decoding_strategy,
outputs=temperature,
)
top_p = gr.Slider(
minimum=0.01,
maximum=0.99,
value=0.8,
step=0.01,
interactive=True,
visible=True,
label="Top P",
info="Higher values is equivalent to sampling more low-probability tokens.",
)
decoding_strategy.change(
fn=lambda selection: gr.Slider.update(visible=(selection in ["Top P Sampling"])),
inputs=decoding_strategy,
outputs=top_p,
)
with gr.Column():
chatbot.render()
def model_inference(
model_selector,
system_prompt,
user_prompt_str,
chat_history,
image,
decoding_strategy,
temperature,
max_new_tokens,
repetition_penalty,
top_p,
):
if user_prompt_str.strip() == "" and image is None:
return "", None, chat_history
system_prompt = ast.literal_eval(system_prompt)
formated_prompt_list, user_prompt_list = format_user_prompt_with_im_history_and_system_conditioning(
system_prompt=system_prompt,
current_user_prompt_str=user_prompt_str.strip(),
current_image=image,
history=chat_history,
)
client_endpoint = API_PATHS[model_selector]
client = Client(
base_url=client_endpoint,
headers={"x-use-cache": "0", "Authorization": f"Bearer {API_TOKEN}"},
)
# Common parameters to all decoding strategies
# This documentation is useful to read: https://huggingface.co/docs/transformers/main/en/generation_strategies
generation_args = {
"max_new_tokens": max_new_tokens,
"repetition_penalty": repetition_penalty,
"stop_sequences": EOS_STRINGS,
}
assert decoding_strategy in [
"Greedy",
"Top P Sampling",
]
if decoding_strategy == "Greedy":
generation_args["do_sample"] = False
elif decoding_strategy == "Top P Sampling":
generation_args["temperature"] = temperature
generation_args["do_sample"] = True
generation_args["top_p"] = top_p
if image is None:
# Case where there is no image OR the image is passed as `<fake_token_around_image><image:IMAGE_URL><fake_token_around_image>`
chat_history.append([prompt_list_to_markdown(user_prompt_list), ''])
else:
# Case where the image is passed through the Image Box.
# Convert the image into base64 for both passing it through the chat history and
# displaying the image inside the same bubble as the text.
chat_history.append(
[
f"{prompt_list_to_markdown([image] + user_prompt_list)}",
'',
]
)
query = prompt_list_to_tgi_input(formated_prompt_list)
stream = client.generate_stream(prompt=query, **generation_args)
acc_text = ""
for idx, response in enumerate(stream):
text_token = response.token.text
if response.details:
# That's the exit condition
return
if text_token in STOP_SUSPECT_LIST:
acc_text += text_token
continue
if idx == 0 and text_token.startswith(" "):
text_token = text_token.lstrip()
acc_text += text_token
last_turn = chat_history.pop(-1)
last_turn[-1] += acc_text
if last_turn[-1].endswith("\nUser"):
# Safeguard: sometimes (rarely), the model won't generate the token `<end_of_utterance>` and will go directly to generating `\nUser:`
# It will thus stop the generation on `\nUser:`. But when it exits, it will have already generated `\nUser`
# This post-processing ensures that we don't have an additional `\nUser` wandering around.
last_turn[-1] = last_turn[-1][:-5]
chat_history.append(last_turn)
yield "", None, chat_history
acc_text = ""
def process_example(message, image):
"""
Same as `model_inference` but in greedy mode and with the 80b-instruct.
Specifically for pre-computing the default examples.
"""
model_selector="HuggingFaceM4/idefics-80b-instruct"
user_prompt_str=message
chat_history=[]
max_new_tokens=512
formated_prompt_list, user_prompt_list = format_user_prompt_with_im_history_and_system_conditioning(
current_user_prompt_str=user_prompt_str.strip(),
current_image=image,
history=chat_history,
)
client_endpoint = API_PATHS[model_selector]
client = Client(
base_url=client_endpoint,
headers={"x-use-cache": "0", "Authorization": f"Bearer {API_TOKEN}"},
timeout=240, # Generous time out just in case because we are in greedy. All examples should be computed in less than 30secs with the 80b-instruct.
)
# Common parameters to all decoding strategies
# This documentation is useful to read: https://huggingface.co/docs/transformers/main/en/generation_strategies
generation_args = {
"max_new_tokens": max_new_tokens,
"repetition_penalty": None,
"stop_sequences": EOS_STRINGS,
"do_sample": False,
}
if image is None:
# Case where there is no image OR the image is passed as `<fake_token_around_image><image:IMAGE_URL><fake_token_around_image>`
chat_history.append([prompt_list_to_markdown(user_prompt_list), ''])
else:
# Case where the image is passed through the Image Box.
# Convert the image into base64 for both passing it through the chat history and
# displaying the image inside the same bubble as the text.
chat_history.append(
[
f"{prompt_list_to_markdown([image] + user_prompt_list)}",
'',
]
)
# Hack - see explanation in `DEFAULT_IMAGES_TMP_PATH_TO_URL`
for idx, i in enumerate(formated_prompt_list):
if i.startswith(DEFAULT_TEMP_DIR):
for k, v in DEFAULT_IMAGES_TMP_PATH_TO_URL.items():
if k == i:
formated_prompt_list[idx] = v
break
query = prompt_list_to_tgi_input(formated_prompt_list)
generated_text = client.generate(prompt=query, **generation_args).generated_text
if generated_text.endswith("\nUser"):
generated_text = generated_text[:-5]
last_turn = chat_history.pop(-1)
last_turn[-1] += generated_text
chat_history.append(last_turn)
return "", None, chat_history
textbox.submit(
fn=model_inference,
inputs=[
model_selector,
system_prompt,
textbox,
chatbot,
imagebox,
decoding_strategy,
temperature,
max_new_tokens,
repetition_penalty,
top_p,
],
outputs=[textbox, imagebox, chatbot],
)
submit_btn.click(
fn=model_inference,
inputs=[
model_selector,
system_prompt,
textbox,
chatbot,
imagebox,
decoding_strategy,
temperature,
max_new_tokens,
repetition_penalty,
top_p,
],
outputs=[
textbox,
imagebox,
chatbot,
],
)
def remove_last_turn(chat_history):
if len(chat_history) == 0:
return gr.Update(), gr.Update()
last_interaction = chat_history[-1]
chat_history = chat_history[:-1]
chat_update = gr.update(value=chat_history)
text_update = gr.update(value=last_interaction[0])
return chat_update, text_update
regenerate_btn.click(fn=remove_last_turn, inputs=chatbot, outputs=[chatbot, textbox]).then(
fn=model_inference,
inputs=[
model_selector,
system_prompt,
textbox,
chatbot,
imagebox,
decoding_strategy,
temperature,
max_new_tokens,
repetition_penalty,
top_p,
],
outputs=[
textbox,
imagebox,
chatbot,
],
)
upload_btn.upload(add_file, [upload_btn], [imagebox, upload_btn], queue=False)
submit_btn.click(lambda : gr.update(label='πŸ“ Upload image', interactive=True), [], upload_btn)
textbox.submit(lambda : gr.update(label='πŸ“ Upload image', interactive=True), [], upload_btn)
clear_btn.click(lambda : gr.update(label='πŸ“ Upload image', interactive=True), [], upload_btn)
examples_path = os.path.dirname(__file__)
gr.Examples(
examples=[
[
"Write a meme text for that image.",
f"{examples_path}/example_images/citibike.webp",
],
[
"Craft a humorous caption for this image!",
f"{examples_path}/example_images/echasse.jpg",
],
[
"How about adding a dash of humor to this image with your words?",
f"{examples_path}/example_images/jesus.jpg",
],
[
"Give this image a comedic twist.",
f"{examples_path}/example_images/owl.jpg",
],
[
"Tell me a joke about that image.",
f"{examples_path}/example_images/pigeon.jpg",
],
[
"Let your sense of humor shine with that image!",
f"{examples_path}/example_images/plotorange.jpg",
],
[
"Make me laugh by commenting that image.",
f"{examples_path}/example_images/rats.jpg",
],
[
"Craft a meme text for that image.",
f"{examples_path}/example_images/sugardaddy.jpg",
],
[
"Write something funny to go with that image!",
f"{examples_path}/example_images/wtf.jpg",
],
],
inputs=[textbox, imagebox],
outputs=[textbox, imagebox, chatbot],
fn=process_example,
cache_examples=False,
examples_per_page=6,
label=(
"Click on any example below to get started."
),
)
gr.HTML("""
<div style="text-align: center; max-width: 650px; margin: 0 auto;">
<p>
Example images from <a href="https://www.instagram.com/whatisnewyork/">Whatisnewyork</a>.
</p>
</div>
""")
demo.queue(concurrency_count=40, max_size=40)
demo.launch()