Spaces:
Runtime error
Runtime error
Create app_Aiden20240322.py
Browse files- app_Aiden20240322.py +90 -0
app_Aiden20240322.py
ADDED
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from transformers import AutoTokenizer, AutoModel, pipeline as transformers_pipeline, AutoModelForCausalLM
|
3 |
+
from diffusers import DiffusionPipeline
|
4 |
+
import requests
|
5 |
+
from PIL import Image
|
6 |
+
import io
|
7 |
+
import torch
|
8 |
+
import torch.nn.functional as F
|
9 |
+
import pandas as pd
|
10 |
+
|
11 |
+
# Function for mean pooling of embeddings
|
12 |
+
def mean_pooling(model_output, attention_mask):
|
13 |
+
token_embeddings = model_output[0] # First element of model_output contains all token embeddings
|
14 |
+
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
|
15 |
+
sum_embeddings = torch.sum(token_embeddings * input_mask_expanded, 1)
|
16 |
+
sum_mask = torch.clamp(input_mask_expanded.sum(1), min=1e-9)
|
17 |
+
return sum_embeddings / sum_mask
|
18 |
+
|
19 |
+
# Load model and tokenizer from HuggingFace Hub for sentence embeddings
|
20 |
+
tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
|
21 |
+
model = AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
|
22 |
+
|
23 |
+
def load_image(input_type, uploaded_file=None, image_url=""):
|
24 |
+
"""
|
25 |
+
Loads an image from an uploaded file or URL.
|
26 |
+
"""
|
27 |
+
if input_type == "Upload Image" and uploaded_file is not None:
|
28 |
+
return Image.open(io.BytesIO(uploaded_file.getvalue()))
|
29 |
+
elif input_type == "Image URL" and image_url:
|
30 |
+
try:
|
31 |
+
response = requests.get(image_url)
|
32 |
+
return Image.open(io.BytesIO(response.content))
|
33 |
+
except Exception as e:
|
34 |
+
st.error(f"Error loading image from URL: {e}")
|
35 |
+
return None
|
36 |
+
|
37 |
+
def image_to_caption(image, input_type, uploaded_file, image_url):
|
38 |
+
"""
|
39 |
+
Generates a caption for the given image.
|
40 |
+
"""
|
41 |
+
image_to_text_pipeline = transformers_pipeline("image-to-text", model="nlpconnect/vit-gpt2-image-captioning")
|
42 |
+
if input_type == "Upload Image" and uploaded_file:
|
43 |
+
return image_to_text_pipeline(uploaded_file.getvalue())[0]['generated_text']
|
44 |
+
elif input_type == "Image URL" and image_url:
|
45 |
+
return image_to_text_pipeline(image_url)[0]['generated_text']
|
46 |
+
return ""
|
47 |
+
|
48 |
+
def select_closest_sentence(generated_text):
|
49 |
+
"""
|
50 |
+
Selects the sentence closest in meaning to the generated_text.
|
51 |
+
"""
|
52 |
+
# Load CSV data
|
53 |
+
df = pd.read_csv('toys_and_games_reviews.csv', encoding='ISO-8859-1')
|
54 |
+
sentences = df.iloc[:, -1].tolist() # Assuming the last column contains sentences
|
55 |
+
|
56 |
+
# Tokenize and compute embeddings for sentences from CSV
|
57 |
+
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
|
58 |
+
with torch.no_grad():
|
59 |
+
model_output = model(**encoded_input)
|
60 |
+
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
|
61 |
+
sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
|
62 |
+
|
63 |
+
# Tokenize and compute embedding for the generated_text
|
64 |
+
encoded_new_sentence = tokenizer([generated_text], padding=True, truncation=True, return_tensors='pt')
|
65 |
+
with torch.no_grad():
|
66 |
+
model_output_new_sentence = model(**encoded_new_sentence)
|
67 |
+
new_sentence_embedding = mean_pooling(model_output_new_sentence, encoded_new_sentence['attention_mask'])
|
68 |
+
new_sentence_embedding = F.normalize(new_sentence_embedding, p=2, dim=1)
|
69 |
+
|
70 |
+
# Find the most similar sentence in your corpus
|
71 |
+
most_similar_idx = F.cosine_similarity(new_sentence_embedding, sentence_embeddings).topk(1).indices.item()
|
72 |
+
most_similar_sentence = sentences[most_similar_idx]
|
73 |
+
|
74 |
+
return most_similar_sentence
|
75 |
+
|
76 |
+
def generate_text_from_caption(caption):
|
77 |
+
"""
|
78 |
+
Generates text based on the provided caption.
|
79 |
+
"""
|
80 |
+
text_generator = transformers_pipeline('text-generation', model='pranavpsv/genre-story-generator-v2')
|
81 |
+
generated = text_generator(caption, max_length=100, num_return_sequences=1)
|
82 |
+
return generated[0]['generated_text']
|
83 |
+
|
84 |
+
def main():
|
85 |
+
st.title('Image to Story to Image Converter')
|
86 |
+
|
87 |
+
# User interface for input selection
|
88 |
+
input_type = st.radio("Select input type:", ("Upload Image", "Image URL"))
|
89 |
+
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"]) if input_type == "Upload Image" else None
|
90 |
+
image_url = st.text_input("Enter the image URL
|