Spaces:
Sleeping
Sleeping
File size: 8,222 Bytes
ed20377 |
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 |
from PIL import Image
import base64
from io import BytesIO
import json
import os
import requests
from typing import Optional
from huggingface_hub import InferenceClient
from transformers import AutoProcessor
from smolagents import Tool
import uuid
import mimetypes
from dotenv import load_dotenv
load_dotenv(override=True)
idefics_processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics2-8b-chatty")
def process_images_and_text(image_path, query, client):
messages = [
{
"role": "user", "content": [
{"type": "image"},
{"type": "text", "text": query},
]
},
]
prompt_with_template = idefics_processor.apply_chat_template(messages, add_generation_prompt=True)
# load images from local directory
# encode images to strings which can be sent to the endpoint
def encode_local_image(image_path):
# load image
image = Image.open(image_path).convert('RGB')
# Convert the image to a base64 string
buffer = BytesIO()
image.save(buffer, format="JPEG") # Use the appropriate format (e.g., JPEG, PNG)
base64_image = base64.b64encode(buffer.getvalue()).decode('utf-8')
# add string formatting required by the endpoint
image_string = f"data:image/jpeg;base64,{base64_image}"
return image_string
image_string = encode_local_image(image_path)
prompt_with_images = prompt_with_template.replace("<image>", " ").format(image_string)
payload = {
"inputs": prompt_with_images,
"parameters": {
"return_full_text": False,
"max_new_tokens": 200,
}
}
return json.loads(client.post(json=payload).decode())[0]
# Function to encode the image
def encode_image(image_path):
if image_path.startswith("http"):
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"
request_kwargs = {
"headers": {"User-Agent": user_agent},
"stream": True,
}
# Send a HTTP request to the URL
response = requests.get(image_path, **request_kwargs)
response.raise_for_status()
content_type = response.headers.get("content-type", "")
extension = mimetypes.guess_extension(content_type)
if extension is None:
extension = ".download"
fname = str(uuid.uuid4()) + extension
download_path = os.path.abspath(os.path.join("downloads", fname))
with open(download_path, "wb") as fh:
for chunk in response.iter_content(chunk_size=512):
fh.write(chunk)
image_path = download_path
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}"
}
def resize_image(image_path):
img = Image.open(image_path)
width, height = img.size
img = img.resize((int(width / 2), int(height / 2)))
new_image_path = f"resized_{image_path}"
img.save(new_image_path)
return new_image_path
class VisualQATool(Tool):
name = "visualizer"
description = "A tool that can answer questions about attached images."
inputs = {
"question": {
"description": "the question to answer",
"type": "string",
"nullable": True,
},
"image_path": {
"description": "The path to the image on which to answer the question",
"type": "string",
},
}
output_type = "string"
client = InferenceClient("HuggingFaceM4/idefics2-8b-chatty")
def forward(self, image_path: str, question: Optional[str] = None) -> str:
add_note = False
if not question:
add_note = True
question = "Please write a detailed caption for this image."
try:
output = process_images_and_text(image_path, question, self.client)
except Exception as e:
print(e)
if "Payload Too Large" in str(e):
new_image_path = resize_image(image_path)
output = process_images_and_text(new_image_path, question, self.client)
if add_note:
output = f"You did not provide a particular question, so here is a detailed caption for the image: {output}"
return output
# ////////////////////////////////////////////////////////////////////////
# import base64
# import json
# import os
# import uuid
# import mimetypes
# from io import BytesIO
# from typing import Optional
# from PIL import Image
# from dotenv import load_dotenv
# import requests
# from smolagents import Tool
# from huggingface_hub import InferenceClient
# load_dotenv()
# # === UTILS ===
# def encode_local_image(image_path):
# image = Image.open(image_path).convert("RGB")
# buffer = BytesIO()
# image.save(buffer, format="JPEG")
# base64_image = base64.b64encode(buffer.getvalue()).decode("utf-8")
# return f"data:image/jpeg;base64,{base64_image}"
# def encode_image(image_path):
# if image_path.startswith("http"):
# user_agent = (
# "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
# "(KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
# )
# response = requests.get(image_path, headers={"User-Agent": user_agent}, stream=True)
# response.raise_for_status()
# ext = mimetypes.guess_extension(response.headers.get("content-type", ""))
# fname = str(uuid.uuid4()) + (ext or ".jpg")
# os.makedirs("downloads", exist_ok=True)
# local_path = os.path.join("downloads", fname)
# with open(local_path, "wb") as f:
# for chunk in response.iter_content(chunk_size=1024):
# f.write(chunk)
# image_path = local_path
# with open(image_path, "rb") as img:
# return base64.b64encode(img.read()).decode("utf-8")
# def resize_image(image_path):
# img = Image.open(image_path)
# width, height = img.size
# img = img.resize((int(width / 2), int(height / 2)))
# new_path = f"resized_{os.path.basename(image_path)}"
# img.save(new_path)
# return new_path
# # === IDEFICS2 Tool ===
# class VisualQATool(Tool):
# name = "visualizer"
# description = "A tool that can answer questions about attached images using IDEFICS2."
# inputs = {
# "question": {
# "description": "The question to answer",
# "type": "string",
# "nullable": True,
# },
# "image_path": {
# "description": "Path to the image (local or downloaded)",
# "type": "string",
# },
# }
# output_type = "string"
# client = InferenceClient("HuggingFaceM4/idefics2-8b-chatty")
# def forward(self, image_path: str, question: Optional[str] = None) -> str:
# add_note = False
# if not question:
# add_note = True
# question = "Please write a detailed caption for this image."
# image_string = encode_local_image(image_path)
# prompt = f"\n\n{question}"
# payload = {
# "inputs": prompt,
# "parameters": {
# "return_full_text": False,
# "max_new_tokens": 200,
# },
# }
# try:
# result = json.loads(self.client.post(json=payload).decode())[0]
# except Exception as e:
# if "Payload Too Large" in str(e):
# resized = resize_image(image_path)
# image_string = encode_local_image(resized)
# prompt = f"\n\n{question}"
# payload["inputs"] = prompt
# result = json.loads(self.client.post(json=payload).decode())[0]
# else:
# raise e
# return (
# f"You did not provide a particular question, so here is a detailed caption for the image: {result}"
# if add_note else result
# )
|