2023-02-24 22:26:15 -05:00
|
|
|
import base64
|
|
|
|
from io import BytesIO
|
|
|
|
|
|
|
|
import gradio as gr
|
2023-02-25 07:23:02 -05:00
|
|
|
import torch
|
|
|
|
from transformers import BlipForConditionalGeneration, BlipProcessor
|
2023-02-24 22:26:15 -05:00
|
|
|
|
2023-03-01 23:23:18 -05:00
|
|
|
import modules.chat as chat
|
|
|
|
import modules.shared as shared
|
|
|
|
|
2023-02-25 00:13:24 -05:00
|
|
|
# If 'state' is True, will hijack the next chat generation with
|
2023-02-25 07:23:02 -05:00
|
|
|
# custom input text given by 'value' in the format [text, visible_text]
|
2023-02-24 22:26:15 -05:00
|
|
|
input_hijack = {
|
2023-02-25 00:13:24 -05:00
|
|
|
'state': False,
|
2023-02-24 23:08:17 -05:00
|
|
|
'value': ["", ""]
|
2023-02-24 22:49:18 -05:00
|
|
|
}
|
|
|
|
|
2023-02-25 01:00:19 -05:00
|
|
|
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
|
|
|
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base", torch_dtype=torch.float32).to("cpu")
|
|
|
|
|
|
|
|
def caption_image(raw_image):
|
|
|
|
inputs = processor(raw_image.convert('RGB'), return_tensors="pt").to("cpu", torch.float32)
|
|
|
|
out = model.generate(**inputs, max_new_tokens=100)
|
|
|
|
return processor.decode(out[0], skip_special_tokens=True)
|
|
|
|
|
2023-02-24 22:26:15 -05:00
|
|
|
def generate_chat_picture(picture, name1, name2):
|
|
|
|
text = f'*{name1} sends {name2} a picture that contains the following: "{caption_image(picture)}"*'
|
|
|
|
buffer = BytesIO()
|
|
|
|
picture.save(buffer, format="JPEG")
|
|
|
|
img_str = base64.b64encode(buffer.getvalue()).decode('utf-8')
|
|
|
|
visible_text = f'<img src="data:image/jpeg;base64,{img_str}">'
|
|
|
|
return text, visible_text
|
|
|
|
|
|
|
|
def ui():
|
|
|
|
picture_select = gr.Image(label='Send a picture', type='pil')
|
|
|
|
|
|
|
|
function_call = 'chat.cai_chatbot_wrapper' if shared.args.cai_chat else 'chat.chatbot_wrapper'
|
2023-02-25 07:23:02 -05:00
|
|
|
|
|
|
|
# Prepare the hijack with custom inputs
|
2023-02-24 22:26:15 -05:00
|
|
|
picture_select.upload(lambda picture, name1, name2: input_hijack.update({"state": True, "value": generate_chat_picture(picture, name1, name2)}), [picture_select, shared.gradio['name1'], shared.gradio['name2']], None)
|
2023-02-25 07:23:02 -05:00
|
|
|
|
|
|
|
# Call the generation function
|
2023-02-24 22:26:15 -05:00
|
|
|
picture_select.upload(eval(function_call), shared.input_params, shared.gradio['display'], show_progress=shared.args.no_stream)
|
2023-02-25 07:23:02 -05:00
|
|
|
|
|
|
|
# Clear the picture from the upload field
|
2023-02-24 22:26:15 -05:00
|
|
|
picture_select.upload(lambda : None, [], [picture_select], show_progress=False)
|