AidenYan commited on
Commit
52919d7
·
verified ·
1 Parent(s): 2e34c0e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -47
app.py CHANGED
@@ -1,13 +1,24 @@
1
  import streamlit as st
2
- from transformers import pipeline as transformers_pipeline, AutoTokenizer, AutoModelForCausalLM, AutoModelForSequenceClassification
3
  from diffusers import DiffusionPipeline
4
  import requests
5
  from PIL import Image
6
  import io
 
 
 
7
 
8
- # Load the tokenizer and model for similarity checking
9
- similarity_tokenizer = AutoTokenizer.from_pretrained("AidenYan/MiniLM_L6_v2_finetuned_ISOM5240_Group27")
10
- similarity_model = AutoModelForSequenceClassification.from_pretrained("AidenYan/MiniLM_L6_v2_finetuned_ISOM5240_Group27")
 
 
 
 
 
 
 
 
11
 
12
  def load_image(input_type, uploaded_file=None, image_url=""):
13
  """
@@ -38,22 +49,37 @@ def select_closest_sentence(generated_text):
38
  """
39
  Selects the sentence closest in meaning to the generated_text.
40
  """
41
- # Implement your logic for sentence similarity here.
42
- # This is a placeholder function. You need to implement the logic
43
- # based on your requirements and the similarity model's capabilities.
 
 
 
 
 
 
 
44
 
45
- # For the sake of this example, let's return the generated_text itself.
46
- return generated_text
 
 
 
 
 
 
 
 
 
 
47
 
48
  def generate_text_from_caption(caption):
49
  """
50
  Generates text based on the provided caption.
51
  """
52
- model = AutoModelForCausalLM.from_pretrained('pranavpsv/genre-story-generator-v2')
53
- tokenizer = AutoTokenizer.from_pretrained('pranavpsv/genre-story-generator-v2')
54
- input_ids = tokenizer.encode(caption, return_tensors='pt')
55
- generated_outputs = model.generate(input_ids, max_length=100, num_return_sequences=1)
56
- return tokenizer.decode(generated_outputs[0], skip_special_tokens=True)
57
 
58
  def main():
59
  st.title('Image to Story to Image Converter')
@@ -61,36 +87,4 @@ def main():
61
  # User interface for input selection
62
  input_type = st.radio("Select input type:", ("Upload Image", "Image URL"))
63
  uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"]) if input_type == "Upload Image" else None
64
- image_url = st.text_input("Enter the image URL here:", "") if input_type == "Image URL" else ""
65
-
66
- # Load image based on input selection
67
- image = load_image(input_type, uploaded_file, image_url)
68
- if image:
69
- st.image(image, caption='Selected Image', use_column_width=True)
70
-
71
- # Process image and generate text
72
- if st.button('Generate Caption and Continue'):
73
- if image:
74
- with st.spinner("Processing..."):
75
- # Convert image to text
76
- caption = image_to_caption(image, input_type, uploaded_file, image_url)
77
- st.success(f'Caption: {caption}')
78
-
79
- # Select the closest sentence using the similarity model
80
- closest_sentence = select_closest_sentence(caption)
81
- st.write(f"Selected Sentence: {closest_sentence}")
82
-
83
- # Generate additional text based on the selected sentence
84
- generated_text = generate_text_from_caption(closest_sentence)
85
- st.text_area("Generated Story:", generated_text, height=200)
86
-
87
- # Generate an image from the story
88
- diffusion_pipeline = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0")
89
- generated_images = diffusion_pipeline(generated_text, num_inference_steps=50)
90
- st.image(generated_images.images[0], caption='Generated Image from Story')
91
-
92
- else:
93
- st.error("Please upload an image or enter an image URL first.")
94
-
95
- if __name__ == "__main__":
96
- main()
 
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('AidenYan/MiniLM_L6_v2_finetuned_ISOM5240_Group27')
21
+ model = AutoModel.from_pretrained('AidenYan/MiniLM_L6_v2_finetuned_ISOM5240_Group27')
22
 
23
  def load_image(input_type, uploaded_file=None, image_url=""):
24
  """
 
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')
 
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