iamrobotbear commited on
Commit
587c009
·
1 Parent(s): 5de39f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -29
app.py CHANGED
@@ -1,7 +1,6 @@
1
  import gradio as gr
2
  import torch
3
  from PIL import Image
4
- import pandas as pd
5
  from lavis.models import load_model_and_preprocess
6
  from lavis.processors import load_processor
7
  from transformers import AutoTokenizer, AutoModelForCausalLM
@@ -12,7 +11,7 @@ model_itm, vis_processors, text_processors = load_model_and_preprocess("blip2_im
12
 
13
  # Load tokenizer and model for Image Captioning (TextCaps)
14
  tokenizer_caption = AutoTokenizer.from_pretrained("microsoft/git-large-r-textcaps")
15
- model_caption = AutoModelForCausalLM.from_pretrained("microsoft/git-large-r-textcaps")
16
 
17
  # List of statements for Image-Text Matching
18
  statements = [
@@ -25,41 +24,38 @@ statements = [
25
  'promotes alcohol use as a "rite of passage" to adulthood',
26
  ]
27
 
28
- txts = [text_processors["eval"](statement) for statement in statements]
29
-
30
- # Function to compute Image-Text Matching (ITM) scores for all statements
31
- def compute_itm_scores(image):
32
- pil_image = Image.fromarray(image.astype('uint8'), 'RGB')
33
- img = vis_processors["eval"](pil_image.convert("RGB")).unsqueeze(0).to(device)
34
- results = []
35
- for i, statement in enumerate(statements):
36
- txt = txts[i]
37
- itm_output = model_itm({"image": img, "text_input": txt}, match_head="itm")
38
- itm_scores = torch.nn.functional.softmax(itm_output, dim=1)
39
- score = itm_scores[:, 1].item()
40
- result_text = f'The image and "{statement}" are matched with a probability of {score:.3%}'
41
- results.append(result_text)
42
- output = "\n".join(results)
43
- return output
44
-
45
  # Function to generate image captions using TextCaps
46
- def generate_image_captions():
47
- prompt = "A photo of"
48
- inputs = tokenizer_caption(prompt, return_tensors="pt", padding=True, truncation=True)
49
  outputs = model_caption.generate(**inputs)
50
  caption = tokenizer_caption.decode(outputs[0], skip_special_tokens=True)
51
- return prompt + " " + caption
52
 
53
  # Main function to perform image captioning and image-text matching
54
  def process_images_and_statements(image):
 
 
 
55
  # Generate image captions using TextCaps
56
- captions = generate_image_captions()
57
 
58
- # Compute ITM scores for predefined statements using LAVIS
59
- itm_scores = compute_itm_scores(image)
60
 
61
- # Combine image captions and ITM scores into the output
62
- output = "Image Captions:\n" + captions + "\n\nITM Scores:\n" + itm_scores
 
 
 
 
 
 
 
 
 
 
 
 
63
  return output
64
 
65
  # Gradio interface
@@ -67,4 +63,4 @@ image_input = gr.inputs.Image()
67
  output = gr.outputs.Textbox(label="Results")
68
 
69
  iface = gr.Interface(fn=process_images_and_statements, inputs=image_input, outputs=output, title="Image Captioning and Image-Text Matching")
70
- iface.launch()
 
1
  import gradio as gr
2
  import torch
3
  from PIL import Image
 
4
  from lavis.models import load_model_and_preprocess
5
  from lavis.processors import load_processor
6
  from transformers import AutoTokenizer, AutoModelForCausalLM
 
11
 
12
  # Load tokenizer and model for Image Captioning (TextCaps)
13
  tokenizer_caption = AutoTokenizer.from_pretrained("microsoft/git-large-r-textcaps")
14
+ model_caption = AutoModelForCausalLM.from_pretrained("microsoft/git-large-r-textcaps").to(device)
15
 
16
  # List of statements for Image-Text Matching
17
  statements = [
 
24
  'promotes alcohol use as a "rite of passage" to adulthood',
25
  ]
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  # Function to generate image captions using TextCaps
28
+ def generate_image_captions(image):
29
+ inputs = tokenizer_caption(image, return_tensors="pt", padding=True, truncation=True).to(device)
 
30
  outputs = model_caption.generate(**inputs)
31
  caption = tokenizer_caption.decode(outputs[0], skip_special_tokens=True)
32
+ return caption
33
 
34
  # Main function to perform image captioning and image-text matching
35
  def process_images_and_statements(image):
36
+ pil_image = Image.fromarray(image.astype('uint8'), 'RGB')
37
+ img = vis_processors["eval"](pil_image.convert("RGB")).unsqueeze(0).to(device)
38
+
39
  # Generate image captions using TextCaps
40
+ captions = generate_image_captions(pil_image)
41
 
42
+ # Convert caption to the format expected by the ITM model
43
+ txt = text_processors["eval"](captions)
44
 
45
+ # Compute ITM scores for predefined statements
46
+ itm_output = model_itm({"image": img, "text_input": txt}, match_head="itm")
47
+ itm_scores = torch.nn.functional.softmax(itm_output, dim=1)
48
+ score = itm_scores[:, 1].item()
49
+
50
+ results = [f'Image Caption: "{captions}" with a matching probability of {score:.3%}']
51
+ for statement in statements:
52
+ txt = text_processors["eval"](statement)
53
+ itm_output = model_itm({"image": img, "text_input": txt}, match_head="itm")
54
+ itm_scores = torch.nn.functional.softmax(itm_output, dim=1)
55
+ score = itm_scores[:, 1].item()
56
+ result_text = f'The combination of image, caption ("{captions}"), and statement ("{statement}") is matched with a probability of {score:.3%}'
57
+ results.append(result_text)
58
+ output = "\n".join(results)
59
  return output
60
 
61
  # Gradio interface
 
63
  output = gr.outputs.Textbox(label="Results")
64
 
65
  iface = gr.Interface(fn=process_images_and_statements, inputs=image_input, outputs=output, title="Image Captioning and Image-Text Matching")
66
+ iface.launch()