Spaces:
Build error
Build error
Commit
·
c19e7bb
1
Parent(s):
35e0000
output name in csv?
Browse files
app.py
CHANGED
|
@@ -1,136 +1,93 @@
|
|
| 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 |
-
|
| 13 |
-
import
|
| 14 |
-
|
| 15 |
-
# Configure logging
|
| 16 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 17 |
|
| 18 |
-
# Load
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
#
|
| 23 |
-
|
| 24 |
-
|
|
|
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
#
|
| 30 |
def compute_textual_similarity(caption, statement):
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
# Calculate cosine similarity between sentence embeddings
|
| 36 |
-
similarity_score = cosine_similarity([caption_embedding], [statement_embedding])[0][0]
|
| 37 |
-
return similarity_score
|
| 38 |
|
| 39 |
-
#
|
| 40 |
-
with open('statements.txt', 'r') as file:
|
| 41 |
-
statements = file.read().splitlines()
|
| 42 |
-
|
| 43 |
-
# Function to compute ITM scores for the image-statement pair
|
| 44 |
def compute_itm_score(image, statement):
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 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 |
-
logging.info('Starting generate_caption')
|
| 57 |
-
inputs = processor(images=image, return_tensors="pt").to(device)
|
| 58 |
-
generated_ids = model.generate(pixel_values=inputs.pixel_values, max_length=50)
|
| 59 |
-
generated_caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 60 |
-
logging.info('Finished generate_caption')
|
| 61 |
-
return generated_caption
|
| 62 |
|
|
|
|
| 63 |
def save_dataframe_to_csv(df):
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
csv_string = csv_buffer.getvalue()
|
| 67 |
-
|
| 68 |
-
# Save the CSV string to a temporary file
|
| 69 |
-
with tempfile.NamedTemporaryFile(mode="w+", delete=False, suffix=".csv") as temp_file:
|
| 70 |
-
temp_file.write(csv_string)
|
| 71 |
-
temp_file_path = temp_file.name # Get the file path
|
| 72 |
-
|
| 73 |
-
# Return the file path (no need to reopen the file with "rb" mode)
|
| 74 |
-
return temp_file_path
|
| 75 |
|
| 76 |
# Main function to perform image captioning and image-text matching
|
| 77 |
-
def
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
# Generate image caption for the uploaded image using git-large-r-textcaps
|
| 81 |
caption = generate_caption(git_processor_large_textcaps, git_model_large_textcaps, image)
|
| 82 |
-
|
| 83 |
-
# Define weights for combining textual similarity score and image-statement ITM score (adjust as needed)
|
| 84 |
-
weight_textual_similarity = 0.5
|
| 85 |
-
weight_statement = 0.5
|
| 86 |
-
|
| 87 |
-
# Initialize an empty list to store the results
|
| 88 |
-
results_list = []
|
| 89 |
-
|
| 90 |
-
# Loop through each predefined statement
|
| 91 |
for statement in statements:
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
# Combine the two scores using a weighted average
|
| 99 |
-
final_score = ((weight_textual_similarity * textual_similarity_score) +
|
| 100 |
-
(weight_statement * itm_score_statement))
|
| 101 |
-
|
| 102 |
-
# Append the result to the results_list
|
| 103 |
-
results_list.append({
|
| 104 |
'Statement': statement,
|
| 105 |
-
'Generated Caption': caption,
|
| 106 |
-
'Textual Similarity Score': f"{textual_similarity_score:.2f}%",
|
| 107 |
-
'ITM Score': f"{itm_score_statement:.2f}%",
|
| 108 |
-
'Final Combined Score': f"{final_score:.2f}%"
|
| 109 |
})
|
| 110 |
-
|
| 111 |
-
# Convert the results_list to a DataFrame using pandas.concat
|
| 112 |
-
results_df = pd.concat([pd.DataFrame([result]) for result in results_list], ignore_index=True)
|
| 113 |
-
|
| 114 |
-
logging.info('Finished process_images_and_statements')
|
| 115 |
-
|
| 116 |
-
# Save results_df to a CSV file
|
| 117 |
csv_results = save_dataframe_to_csv(results_df)
|
|
|
|
| 118 |
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
| 121 |
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
output_df = gr.outputs.Dataframe(type="pandas", label="Results")
|
| 125 |
output_csv = gr.outputs.File(label="Download CSV")
|
| 126 |
|
| 127 |
iface = gr.Interface(
|
| 128 |
-
fn=
|
| 129 |
inputs=image_input,
|
| 130 |
-
outputs=[output_df, output_csv],
|
| 131 |
title="Image Captioning and Image-Text Matching",
|
| 132 |
theme='sudeepshouche/minimalist',
|
| 133 |
-
css=".output { flex-direction: column; } .output .outputs { width: 100%; }" # Custom CSS
|
|
|
|
| 134 |
)
|
| 135 |
|
| 136 |
-
iface.launch()
|
|
|
|
| 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
|
| 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 |
+
# List of statements for Image-Text Matching
|
| 17 |
+
statements = [
|
| 18 |
+
# (List of statements as provided in the original code)
|
| 19 |
+
]
|
| 20 |
|
| 21 |
+
# Function to generate image caption
|
| 22 |
+
def generate_caption(processor, model, image):
|
| 23 |
+
inputs = processor(images=image, return_tensors="pt")
|
| 24 |
+
outputs = model(**inputs)
|
| 25 |
+
caption = processor.batch_decode(outputs.logits.argmax(-1), skip_special_tokens=True)
|
| 26 |
+
return caption[0]
|
| 27 |
|
| 28 |
+
# Function to compute textual similarity
|
| 29 |
def compute_textual_similarity(caption, statement):
|
| 30 |
+
captions_embeddings = use_model([caption])[0].numpy()
|
| 31 |
+
statements_embeddings = use_model([statement])[0].numpy()
|
| 32 |
+
similarity_score = np.inner(captions_embeddings, statements_embeddings)
|
| 33 |
+
return similarity_score[0]
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
+
# Function to compute ITM score
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
def compute_itm_score(image, statement):
|
| 37 |
+
image_features = itm_model(image)
|
| 38 |
+
statement_features = use_model([statement])[0].numpy()
|
| 39 |
+
similarity_score = np.inner(image_features, statement_features)
|
| 40 |
+
return similarity_score[0][0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
+
# Function to save DataFrame to CSV
|
| 43 |
def save_dataframe_to_csv(df):
|
| 44 |
+
csv_data = df.to_csv(index=False)
|
| 45 |
+
return csv_data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
# Main function to perform image captioning and image-text matching
|
| 48 |
+
def process_image_and_statements(image, file_name):
|
| 49 |
+
all_results_list = []
|
|
|
|
|
|
|
| 50 |
caption = generate_caption(git_processor_large_textcaps, git_model_large_textcaps, image)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
for statement in statements:
|
| 52 |
+
textual_similarity_score = compute_textual_similarity(caption, statement) * 100
|
| 53 |
+
itm_score_statement = compute_itm_score(image, statement) * 100
|
| 54 |
+
final_score = 0.5 * textual_similarity_score + 0.5 * itm_score_statement
|
| 55 |
+
all_results_list.append({
|
| 56 |
+
'Image File Name': file_name, # Include the image file name
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
'Statement': statement,
|
| 58 |
+
'Generated Caption': caption,
|
| 59 |
+
'Textual Similarity Score': f"{textual_similarity_score:.2f}%",
|
| 60 |
+
'ITM Score': f"{itm_score_statement:.2f}%",
|
| 61 |
+
'Final Combined Score': f"{final_score:.2f}%"
|
| 62 |
})
|
| 63 |
+
results_df = pd.DataFrame(all_results_list)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
csv_results = save_dataframe_to_csv(results_df)
|
| 65 |
+
return results_df, csv_results
|
| 66 |
|
| 67 |
+
# Gradio interface with Image input to receive an image and its file name
|
| 68 |
+
image_input = gr.inputs.Image(label="Upload Image", image_mode='RGB', source="upload")
|
| 69 |
+
output_df = gr.outputs.Dataframe(type="pandas", label="Results")
|
| 70 |
+
output_csv = gr.outputs.File(label="Download CSV")
|
| 71 |
|
| 72 |
+
iface = gr.Interface(
|
| 73 |
+
fn=process_image_and_statements,
|
| 74 |
+
inputs=image_input,
|
| 75 |
+
outputs=[output_df, output_csv],
|
| 76 |
+
title="Image Captioning and Image-Text Matching",
|
| 77 |
+
|
| 78 |
+
# Gradio interface with Image input to receive an image and its file name
|
| 79 |
+
image_input = gr.inputs.Image(label="Upload Image", image_mode='RGB', source="upload")
|
| 80 |
output_df = gr.outputs.Dataframe(type="pandas", label="Results")
|
| 81 |
output_csv = gr.outputs.File(label="Download CSV")
|
| 82 |
|
| 83 |
iface = gr.Interface(
|
| 84 |
+
fn=process_image_and_statements,
|
| 85 |
inputs=image_input,
|
| 86 |
+
outputs=[output_df, output_csv],
|
| 87 |
title="Image Captioning and Image-Text Matching",
|
| 88 |
theme='sudeepshouche/minimalist',
|
| 89 |
+
css=".output { flex-direction: column; } .output .outputs { width: 100%; }", # Custom CSS
|
| 90 |
+
capture_session=True, # Capture errors and exceptions in Gradio interface
|
| 91 |
)
|
| 92 |
|
| 93 |
+
iface.launch(debug=True)
|