Spaces:
Build error
Build error
Commit
·
893a3e5
1
Parent(s):
1e2e099
Update app.py
Browse files
app.py
CHANGED
@@ -1,77 +1,47 @@
|
|
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, AutoProcessor
|
8 |
import tensorflow as tf
|
9 |
import tensorflow_hub as hub
|
10 |
-
import
|
11 |
-
|
12 |
-
import
|
13 |
-
import
|
14 |
-
|
15 |
-
# Configure logging
|
16 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
17 |
-
|
18 |
-
# Load model and preprocessors for Image-Text Matching (LAVIS)
|
19 |
-
device = torch.device("cuda") if torch.cuda.is_available() else "cpu"
|
20 |
-
model_itm, vis_processors, text_processors = load_model_and_preprocess("blip2_image_text_matching", "pretrain", device=device, is_eval=True)
|
21 |
-
|
22 |
-
# Load tokenizer and model for Image Captioning (TextCaps)
|
23 |
-
git_processor_large_textcaps = AutoProcessor.from_pretrained("microsoft/git-large-r-textcaps")
|
24 |
-
git_model_large_textcaps = AutoModelForCausalLM.from_pretrained("microsoft/git-large-r-textcaps")
|
25 |
-
|
26 |
-
# Load Universal Sentence Encoder model for textual similarity calculation
|
27 |
-
embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
|
28 |
-
|
29 |
-
# Define a function to compute textual similarity between caption and statement
|
30 |
-
def compute_textual_similarity(caption, statement):
|
31 |
-
# Convert caption and statement into sentence embeddings
|
32 |
-
caption_embedding = embed([caption])[0].numpy()
|
33 |
-
statement_embedding = embed([statement])[0].numpy()
|
34 |
|
35 |
-
|
36 |
-
|
37 |
-
|
|
|
|
|
|
|
38 |
|
39 |
# Read statements from the external file 'statements.txt'
|
40 |
with open('statements.txt', 'r') as file:
|
41 |
statements = file.read().splitlines()
|
42 |
|
43 |
-
# Function to
|
44 |
-
def compute_itm_score(image, statement):
|
45 |
-
logging.info('Starting compute_itm_score')
|
46 |
-
pil_image = Image.fromarray(image.astype('uint8'), 'RGB')
|
47 |
-
img = vis_processors["eval"](pil_image.convert("RGB")).unsqueeze(0).to(device)
|
48 |
-
# Pass the statement text directly to model_itm
|
49 |
-
itm_output = model_itm({"image": img, "text_input": statement}, match_head="itm")
|
50 |
-
itm_scores = torch.nn.functional.softmax(itm_output, dim=1)
|
51 |
-
score = itm_scores[:, 1].item()
|
52 |
-
logging.info('Finished compute_itm_score')
|
53 |
-
return score
|
54 |
-
|
55 |
def generate_caption(processor, model, image):
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
logging.info('Finished generate_caption')
|
61 |
-
return generated_caption
|
62 |
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
|
|
|
|
67 |
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
|
|
|
|
72 |
|
73 |
-
|
74 |
-
|
|
|
|
|
75 |
|
76 |
# Main function to perform image captioning and image-text matching for multiple images
|
77 |
def process_images_and_statements(files):
|
@@ -81,7 +51,10 @@ def process_images_and_statements(files):
|
|
81 |
if isinstance(files, list):
|
82 |
files = {f.name: f for f in files}
|
83 |
|
84 |
-
for file_name,
|
|
|
|
|
|
|
85 |
caption = generate_caption(git_processor_large_textcaps, git_model_large_textcaps, image)
|
86 |
for statement in statements:
|
87 |
textual_similarity_score = compute_textual_similarity(caption, statement) * 100
|
@@ -99,6 +72,7 @@ def process_images_and_statements(files):
|
|
99 |
csv_results = save_dataframe_to_csv(results_df)
|
100 |
return results_df, csv_results
|
101 |
|
|
|
102 |
# Gradio interface with File input to receive multiple images and file names
|
103 |
image_input = gr.inputs.File(file_count="multiple", type="file", label="Upload Images")
|
104 |
output_df = gr.outputs.Dataframe(type="pandas", label="Results")
|
@@ -110,7 +84,8 @@ iface = gr.Interface(
|
|
110 |
outputs=[output_df, output_csv],
|
111 |
title="Image Captioning and Image-Text Matching",
|
112 |
theme='sudeepshouche/minimalist',
|
113 |
-
css=".output { flex-direction: column; } .output .outputs { width: 100%; }" # Custom CSS
|
|
|
114 |
)
|
115 |
|
116 |
iface.launch(debug=True)
|
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
import tensorflow as tf
|
3 |
import tensorflow_hub as hub
|
4 |
+
import numpy as np
|
5 |
+
import pandas as pd
|
6 |
+
from transformers import GitProcessor, GitModel, GitConfig, ImageFeatureProcessor
|
7 |
+
from PIL import Image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
+
# Load models and processors
|
10 |
+
git_config = GitConfig.from_pretrained("microsoft/git-large-r")
|
11 |
+
git_processor_large_textcaps = GitProcessor.from_pretrained("microsoft/git-large-r")
|
12 |
+
git_model_large_textcaps = GitModel.from_pretrained("microsoft/git-large-r")
|
13 |
+
itm_model = hub.load("https://tfhub.dev/google/LaViT/1")
|
14 |
+
use_model = hub.load("https://tfhub.dev/google/universal-sentence-encoder-large/5")
|
15 |
|
16 |
# Read statements from the external file 'statements.txt'
|
17 |
with open('statements.txt', 'r') as file:
|
18 |
statements = file.read().splitlines()
|
19 |
|
20 |
+
# Function to generate image caption
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
def generate_caption(processor, model, image):
|
22 |
+
inputs = processor(images=image, return_tensors="pt")
|
23 |
+
outputs = model(**inputs)
|
24 |
+
caption = processor.batch_decode(outputs.logits.argmax(-1), skip_special_tokens=True)
|
25 |
+
return caption[0]
|
|
|
|
|
26 |
|
27 |
+
# Function to compute textual similarity
|
28 |
+
def compute_textual_similarity(caption, statement):
|
29 |
+
captions_embeddings = use_model([caption])[0].numpy()
|
30 |
+
statements_embeddings = use_model([statement])[0].numpy()
|
31 |
+
similarity_score = np.inner(captions_embeddings, statements_embeddings)
|
32 |
+
return similarity_score[0]
|
33 |
|
34 |
+
# Function to compute ITM score
|
35 |
+
def compute_itm_score(image, statement):
|
36 |
+
image_features = itm_model(image)
|
37 |
+
statement_features = use_model([statement])[0].numpy()
|
38 |
+
similarity_score = np.inner(image_features, statement_features)
|
39 |
+
return similarity_score[0][0]
|
40 |
|
41 |
+
# Function to save DataFrame to CSV
|
42 |
+
def save_dataframe_to_csv(df):
|
43 |
+
csv_data = df.to_csv(index=False)
|
44 |
+
return csv_data
|
45 |
|
46 |
# Main function to perform image captioning and image-text matching for multiple images
|
47 |
def process_images_and_statements(files):
|
|
|
51 |
if isinstance(files, list):
|
52 |
files = {f.name: f for f in files}
|
53 |
|
54 |
+
for file_name, image_file in files.items():
|
55 |
+
# Convert the image file to a PIL image
|
56 |
+
image = Image.open(image_file)
|
57 |
+
|
58 |
caption = generate_caption(git_processor_large_textcaps, git_model_large_textcaps, image)
|
59 |
for statement in statements:
|
60 |
textual_similarity_score = compute_textual_similarity(caption, statement) * 100
|
|
|
72 |
csv_results = save_dataframe_to_csv(results_df)
|
73 |
return results_df, csv_results
|
74 |
|
75 |
+
# Gradio interface with File input to receive
|
76 |
# Gradio interface with File input to receive multiple images and file names
|
77 |
image_input = gr.inputs.File(file_count="multiple", type="file", label="Upload Images")
|
78 |
output_df = gr.outputs.Dataframe(type="pandas", label="Results")
|
|
|
84 |
outputs=[output_df, output_csv],
|
85 |
title="Image Captioning and Image-Text Matching",
|
86 |
theme='sudeepshouche/minimalist',
|
87 |
+
css=".output { flex-direction: column; } .output .outputs { width: 100%; }", # Custom CSS
|
88 |
+
capture_session=True, # Capture errors and exceptions in Gradio interface
|
89 |
)
|
90 |
|
91 |
iface.launch(debug=True)
|