Event 42 commited on
Commit
b36caa0
1 Parent(s): 6b9f122

Add aplication file2

Browse files
Files changed (1) hide show
  1. app.py +47 -4
app.py CHANGED
@@ -1,4 +1,47 @@
1
- import gradio
2
- app = gradio.Interface(
3
-
4
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ import requests
4
+
5
+ from PIL import Image
6
+ from transformers import AutoProcessor, AutoModelForVision2Seq
7
+
8
+
9
+ model = AutoModelForVision2Seq.from_pretrained("microsoft/kosmos-2-patch14-224")
10
+ processor = AutoProcessor.from_pretrained("microsoft/kosmos-2-patch14-224")
11
+
12
+ prompt = "<grounding>An image of"
13
+
14
+ url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.png"
15
+ image = Image.open(requests.get(url, stream=True).raw)
16
+
17
+ # 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.
18
+ image.save("new_image.jpg")
19
+ image = Image.open("new_image.jpg")
20
+
21
+ inputs = processor(text=prompt, images=image, return_tensors="pt")
22
+
23
+ generated_ids = model.generate(
24
+ pixel_values=inputs["pixel_values"],
25
+ input_ids=inputs["input_ids"],
26
+ attention_mask=inputs["attention_mask"],
27
+ image_embeds=None,
28
+ image_embeds_position_mask=inputs["image_embeds_position_mask"],
29
+ use_cache=True,
30
+ max_new_tokens=128,
31
+ )
32
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
33
+
34
+ # Specify `cleanup_and_extract=False` in order to see the raw model generation.
35
+ processed_text = processor.post_process_generation(generated_text, cleanup_and_extract=False)
36
+
37
+ print(processed_text)
38
+ # `<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>.`
39
+
40
+ # By default, the generated text is cleanup and the entities are extracted.
41
+ processed_text, entities = processor.post_process_generation(generated_text)
42
+
43
+ print(processed_text)
44
+ # `An image of a snowman warming himself by a fire.`
45
+
46
+ print(entities)
47
+ # `[('a snowman', (12, 21), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a fire', (41, 47), [(0.171875, 0.015625, 0.484375, 0.890625)])]`