(There is an on going effort to port
Kosmos-2
directly into
transformers
. This repository (remote code) might need some more bug fixes later, including breaking changes.)
This Hub repository contains a HuggingFace's
transformers
implementation of
the original Kosmos-2 model
from Microsoft.
How to Get Started with the Model
Use the code below to get started with the model.
import requests
from PIL import Image
from transformers import AutoProcessor, AutoModelForVision2Seq
model = AutoModelForVision2Seq.from_pretrained("ydshieh/kosmos-2-patch14-224", trust_remote_code=True)
processor = AutoProcessor.from_pretrained("ydshieh/kosmos-2-patch14-224", trust_remote_code=True)
prompt = "<grounding>An image of"
url = "https://huggingface.co/ydshieh/kosmos-2-patch14-224/resolve/main/snowman.png"
image = Image.open(requests.get(url, stream=True).raw)
# The original Kosmos-2 demo saves the image first then reload it. For some images, this will give slightly different image input and change the generation outputs.# Uncomment the following 2 lines if you want to match the original demo's outputs.# (One example is the `two_dogs.jpg` from the demo)# image.save("new_image.jpg")# image = Image.open("new_image.jpg")
inputs = processor(text=prompt, images=image, return_tensors="pt")
generated_ids = model.generate(
pixel_values=inputs["pixel_values"],
input_ids=inputs["input_ids"][:, :-1],
attention_mask=inputs["attention_mask"][:, :-1],
img_features=None,
img_attn_mask=inputs["img_attn_mask"][:, :-1],
use_cache=True,
max_new_tokens=64,
)
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
# Specify `cleanup_and_extract=False` in order to see the raw model generation.
processed_text = processor.post_process_generation(generated_text, cleanup_and_extract=False)
print(processed_text)
# `<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911></object>.`# By default, the generated text is cleanup and the entities are extracted.
processed_text, entities = processor.post_process_generation(generated_text)
print(processed_text)
# `An image of a snowman warming himself by a fire.`print(entities)
# `[('a snowman', (12, 21), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a fire', (41, 47), [(0.171875, 0.015625, 0.484375, 0.890625)])]`
Draw the bounding bboxes of the entities on the image
Once you have the
entities
, you can use the following helper function to draw their bounding bboxes on the image:
prompt = "<grounding><phrase> a snowman</phrase>"
run_example(prompt)
# a snowman is warming himself by the fire# [('a snowman', (0, 9), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('the fire', (32, 40), [(0.203125, 0.015625, 0.453125, 0.859375)])]# <grounding><phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> is warming himself by<phrase> the fire</phrase><object><patch_index_0006><patch_index_0878></object>
• Referring Expression Comprehension
prompt = "<grounding><phrase> a snowman next to a fire</phrase>"
run_example(prompt)
# a snowman next to a fire# [('a snowman next to a fire', (0, 24), [(0.390625, 0.046875, 0.984375, 0.828125)])]# <grounding><phrase> a snowman next to a fire</phrase><object><patch_index_0044><patch_index_0863></object>
Multimodal Referring
• Referring expression generation
prompt = "<grounding><phrase> It</phrase><object><patch_index_0044><patch_index_0863></object> is"
run_example(prompt)
# It is snowman in a hat and scarf# [('It', (0, 2), [(0.390625, 0.046875, 0.984375, 0.828125)])]# <grounding><phrase> It</phrase><object><patch_index_0044><patch_index_0863></object> is snowman in a hat and scarf
Perception-Language Tasks
• Grounded VQA
prompt = "<grounding> Question: What is special about this image? Answer:"
run_example(prompt)
# Question: What is special about this image? Answer: The image features a snowman sitting by a campfire in the snow.# [('a snowman', (71, 80), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a campfire', (92, 102), [(0.109375, 0.640625, 0.546875, 0.984375)])]# <grounding> Question: What is special about this image? Answer: The image features<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> sitting by<phrase> a campfire</phrase><object><patch_index_0643><patch_index_1009></object> in the snow.
• Grounded VQA with multimodal referring via bounding boxes
prompt = "<grounding> Question: Where is<phrase> the fire</phrase><object><patch_index_0005><patch_index_0911></object> next to? Answer:"
run_example(prompt)
# Question: Where is the fire next to? Answer: Near the snowman.# [('the fire', (19, 27), [(0.171875, 0.015625, 0.484375, 0.890625)]), ('the snowman', (50, 61), [(0.390625, 0.046875, 0.984375, 0.828125)])]# <grounding> Question: Where is<phrase> the fire</phrase><object><patch_index_0005><patch_index_0911></object> next to? Answer: Near<phrase> the snowman</phrase><object><patch_index_0044><patch_index_0863></object>.
Grounded Image captioning
• Brief
prompt = "<grounding> An image of"
run_example(prompt)
# An image of a snowman warming himself by a campfire.# [('a snowman', (12, 21), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a campfire', (41, 51), [(0.109375, 0.640625, 0.546875, 0.984375)])]# <grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a campfire</phrase><object><patch_index_0643><patch_index_1009></object>.
• Detailed
prompt = "<grounding> Describe this image in detail:"
run_example(prompt)
# Describe this image in detail: The image features a snowman sitting by a campfire in the snow. He is wearing a hat, scarf, and gloves, with a pot nearby and a cup# [('a campfire', (71, 81), [(0.171875, 0.015625, 0.484375, 0.984375)]), ('a hat', (109, 114), [(0.515625, 0.046875, 0.828125, 0.234375)]), ('scarf', (116, 121), [(0.515625, 0.234375, 0.890625, 0.578125)]), ('gloves', (127, 133), [(0.515625, 0.390625, 0.640625, 0.515625)]), ('a pot', (140, 145), [(0.078125, 0.609375, 0.265625, 0.859375)])]# <grounding> Describe this image in detail: The image features a snowman sitting by<phrase> a campfire</phrase><object><patch_index_0005><patch_index_1007></object> in the snow. He is wearing<phrase> a hat</phrase><object><patch_index_0048><patch_index_0250></object>,<phrase> scarf</phrase><object><patch_index_0240><patch_index_0604></object>, and<phrase> gloves</phrase><object><patch_index_0400><patch_index_0532></object>, with<phrase> a pot</phrase><object><patch_index_0610><patch_index_0872></object> nearby and<phrase> a cup</phrase><object>
Running the Flask Server
flask_kosmos2.py
shows the implementation of a Flask server for the model.
It allowes the model to be approached as a REST API.
After starting the server. You can send a POST request to
http://localhost:8005/process_prompt
with the following form data:
prompt
: For example
<grounding> an image of
image
: The image file as binary data
This in turn will produce a reply with the following JSON format:
message
: The Kosmos-2 generated text
entities
: The extracted entities
An easy way to test this is through an application like Postman. Make sure the image field is set to
File
.
from PIL import Image
from transformers import AutoProcessor, AutoModelForVision2Seq
from flask import Flask, request, jsonify
import json
app = Flask(__name__)
model = AutoModelForVision2Seq.from_pretrained("ydshieh/kosmos-2-patch14-224", trust_remote_code=True)
processor = AutoProcessor.from_pretrained("ydshieh/kosmos-2-patch14-224", trust_remote_code=True)
@app.route('/process_prompt', methods=['POST'])defprocess_prompt():
try:
# Get the uploaded image data from the POST request
uploaded_file = request.files['image']
prompt = request.form.get('prompt')
image = Image.open(uploaded_file.stream)
print(image.size)
inputs = processor(text=prompt, images=image, return_tensors="pt")
generated_ids = model.generate(
pixel_values=inputs["pixel_values"],
input_ids=inputs["input_ids"][:, :-1],
attention_mask=inputs["attention_mask"][:, :-1],
img_features=None,
img_attn_mask=inputs["img_attn_mask"][:, :-1],
use_cache=True,
max_new_tokens=64,
)
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
# By default, the generated text is cleanup and the entities are extracted.
processed_text, entities = processor.post_process_generation(generated_text)
parsed_entities = entities_to_json(entities)
print(generated_text)
print(processed_text)
return jsonify({"message": processed_text, 'entities': parsed_entities})
except Exception as e:
return jsonify({"error": str(e)})
defentities_to_json(entities):
result = []
for e in entities:
label = e[0]
box_coords = e[1]
box_size = e[2][0]
entity_result = {
"label": label,
"boundingBoxPosition": {"x": box_coords[0], "y": box_coords[1]},
"boundingBox": {"x_min": box_size[0], "y_min": box_size[1], "x_max": box_size[2], "y_max": box_size[3]}
}
print(entity_result)
result.append(entity_result)
return result
if __name__ == '__main__':
app.run(host='localhost', port=8005)
Runs of ydshieh kosmos-2-patch14-224 on huggingface.co
101
Total runs
0
24-hour runs
0
3-day runs
-8
7-day runs
50
30-day runs
More Information About kosmos-2-patch14-224 huggingface.co Model
kosmos-2-patch14-224 huggingface.co
kosmos-2-patch14-224 huggingface.co is an AI model on huggingface.co that provides kosmos-2-patch14-224's model effect (), which can be used instantly with this ydshieh kosmos-2-patch14-224 model. huggingface.co supports a free trial of the kosmos-2-patch14-224 model, and also provides paid use of the kosmos-2-patch14-224. Support call kosmos-2-patch14-224 model through api, including Node.js, Python, http.
kosmos-2-patch14-224 huggingface.co is an online trial and call api platform, which integrates kosmos-2-patch14-224's modeling effects, including api services, and provides a free online trial of kosmos-2-patch14-224, you can try kosmos-2-patch14-224 online for free by clicking the link below.
ydshieh kosmos-2-patch14-224 online free url in huggingface.co:
kosmos-2-patch14-224 is an open source model from GitHub that offers a free installation service, and any user can find kosmos-2-patch14-224 on GitHub to install. At the same time, huggingface.co provides the effect of kosmos-2-patch14-224 install, users can directly use kosmos-2-patch14-224 installed effect in huggingface.co for debugging and trial. It also supports api for free installation.
kosmos-2-patch14-224 install url in huggingface.co: