witchEverly commited on
Commit
db3cf05
·
verified ·
1 Parent(s): 1bfdf2c

Update app.py

Browse files

changes made to reflect app2

Files changed (1) hide show
  1. app.py +93 -74
app.py CHANGED
@@ -1,98 +1,117 @@
1
  import streamlit as st
2
- from PIL import Image, ImageOps
3
- import numpy as np
4
- import pickle
5
  from torchvision import transforms
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
-
8
- # use $ streamlit run app.py to run app!
9
-
10
- # hide deprication warnings
11
- import warnings
12
- warnings.filterwarnings("ignore")
13
-
14
- # BLIP Model
15
- from transformers import BlipForConditionalGeneration, BlipProcessor
16
- blip_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
17
- blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
18
-
19
- # Caption Model
20
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
21
- caption_tokenizer = AutoTokenizer.from_pretrained("prasanthsagirala/text-to-social-media-captions")
22
- caption_model = AutoModelForSeq2SeqLM.from_pretrained("prasanthsagirala/text-to-social-media-captions")
23
-
24
- # with open("models/blip_model.pkl", "rb") as f:
25
- # blip_model = pickle.load(f)
26
-
27
- # with open("models/caption_tokenizer.pkl", "rb") as f:
28
- # caption_tokenizer = pickle.load(f)
29
-
30
- # with open("models/caption_model.pkl", "rb") as f:
31
- # caption_model = pickle.load(f)
32
-
 
 
 
 
33
 
34
  # Set pre-defined page configurations
35
- st.set_page_config(
36
- page_title="Instamuse", # Title
37
- page_icon=":camera:", # log-icon
38
- initial_sidebar_state='auto' # page loading state
39
- )
40
 
41
- # Sidebard (left side of page)
42
  with st.sidebar:
43
  st.image('insta.png')
44
  st.title("InstaMuse")
45
- st.subheader(
46
- "Welcome to InstaMuse, the ultimate tool for turning your snapshots into social media sensations!")
47
- st.write(
48
- "Start turning heads with your posts. Use InstaMuse now and watch your likes soar! ")
49
 
50
  # Main page text
51
  st.write("""
52
  # InstaMuse 🌟📸
53
 
54
- Struggling to find the perfect words to match your pictures? Let InstaMuse do the heavy \
55
- lifting! With just a simple upload, our app uses cutting-edge technology to analyze your \
56
- image and generate a witty, engaging, or inspiring caption that captures the essence of \
 
57
  your moment. \n \
58
 
59
- Whether you’re a selfie savant, a nature explorer, or a foodie fanatic, InstaMuse is here to \
60
- amplify your Instagram presence. Jazz up your feed with tailored captions that resonate with your \
61
- followers and attract new eyes to your profile. It’s quick, easy, and fun!
 
62
 
63
  **Drag your photo here and spark some caption magic!** ✨
64
  """
65
  )
66
 
67
- # For Bhumika!!!
68
- # Modeling part
69
  file = st.file_uploader("", type=["jpg", "png"])
70
 
71
-
72
- def import_and_predict(image_data): # Will also need to import model I think?
73
- transform = transforms.Compose([
74
- transforms.Resize((1080, 1080))
75
- ])
76
- image = transform(image_data)
77
-
78
- # BLIP Description Generation
79
- inputs = blip_processor(images=image, return_tensors="pt")
80
- generated_ids = blip_model.generate(**inputs, max_new_tokens=50)
81
- generated_text = blip_processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
82
-
83
- # Caption Generation
84
- inputs = ["Instagram captionize:" + generated_text]
85
- inputs = caption_tokenizer(inputs, max_length=512, truncation=True, return_tensors="pt")
86
- output = caption_model.generate(**inputs, num_beams=8, do_sample=True, min_length=10, max_length=64)
87
- decoded_output = caption_tokenizer.batch_decode(output, skip_special_tokens=True)[0]
88
- return decoded_output
89
-
90
-
91
- if file is None:
92
- st.text("Upload your photo now and let the caption fun begin!")
93
  else:
94
- image = Image.open(file).convert('RGB')
95
- st.image(image, use_column_width=True)
96
- predictions = import_and_predict(image)
97
- st.markdown("## Captions:")
98
- st.info(predictions)
 
1
  import streamlit as st
2
+ from PIL import Image
 
 
3
  from torchvision import transforms
4
+ from transformers import AutoProcessor, BlipForConditionalGeneration
5
+ import google.generativeai as genai
6
+
7
+ # Define model
8
+
9
+ # Initialize the image to caption model - BLIP
10
+ blip_processor = AutoProcessor.\
11
+ from_pretrained("Salesforce/blip-image-captioning-base")
12
+ blip_model = BlipForConditionalGeneration.\
13
+ from_pretrained("Salesforce/blip-image-captioning-base")
14
+
15
+ # Initialize the caption to instagram post model - gemini
16
+ GOOGLE_API_KEY = 'AIzaSyDMeFOnOflzYJ-cjedJ8ky9AE-yThcNXFk'
17
+ genai.configure(api_key=GOOGLE_API_KEY)
18
+ gemini_model = genai.GenerativeModel('gemini-pro')
19
+
20
+
21
+ def import_and_predict(image_data):
22
+ """Creates five possible Instagram captions for an image.
23
+ Args:
24
+ - image_data: Image data in RGB format.
25
+ Returns:
26
+ - response.text: The five Instagram captions in text format.
27
+ """
28
+ transform = transforms.Compose([
29
+ transforms.Resize((1080, 1080))
30
+ ])
31
+ uploaded_image = transform(image_data)
32
 
33
+ # BLIP Description Generation
34
+ inputs = blip_processor(images=uploaded_image, return_tensors="pt")
35
+ generated_ids = blip_model.generate(**inputs,
36
+ max_new_tokens=100,
37
+ max_length=100)
38
+ caption = blip_processor.\
39
+ batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
40
+
41
+ # Gemini Caption Generation
42
+ prompt = f"""Given the provided photo caption, generate five distinct \
43
+ and engaging Instagram captions. Each caption must include \
44
+ at least one emoji and one hashtag. The captions should be \
45
+ formatted with a preceding "Caption #", followed by the \
46
+ caption text. Ensure each caption is seperated by a blank \
47
+ line for readability. \
48
+
49
+ Original Caption: {caption}
50
+
51
+ Please format your response as follows:
52
+ **Caption 1**: [caption text] \n
53
+ **Caption 2**: [caption text] \n
54
+ **Caption 3**: [caption text] \n
55
+ **Caption 4**: [caption text] \n
56
+ **Caption 5**: [caption text] \n
57
+ """
58
+ response = gemini_model.generate_content(prompt)
59
+ return response.text
60
+
61
+
62
+ # Define streamlit configurations
63
 
64
  # Set pre-defined page configurations
65
+ st.set_page_config(page_title="Instamuse",
66
+ page_icon=":camera:",
67
+ initial_sidebar_state='auto')
 
 
68
 
69
+ # Sidebar (left side of the page)
70
  with st.sidebar:
71
  st.image('insta.png')
72
  st.title("InstaMuse")
73
+ st.subheader("Welcome to InstaMuse, the ultimate tool for turning your \
74
+ snapshots into social media sensations!")
75
+ st.write("Start turning heads with your posts. Use InstaMuse now and \
76
+ watch your likes soar! ")
77
 
78
  # Main page text
79
  st.write("""
80
  # InstaMuse 🌟📸
81
 
82
+ Struggling to find the perfect words to match your pictures? Let \
83
+ InstaMuse do the heavy lifting! With just a simple upload, our app \
84
+ uses cutting-edge technology to analyze your image and generate a \
85
+ witty, engaging, or inspiring caption that captures the essence of \
86
  your moment. \n \
87
 
88
+ Whether you’re a selfie savant, a nature explorer, or a foodie fanatic\
89
+ , InstaMuse is here to amplify your Instagram presence. Jazz up your \
90
+ feed with tailored captions that resonate with your followers and \
91
+ attract new eyes to your profile. It’s quick, easy, and fun!
92
 
93
  **Drag your photo here and spark some caption magic!** ✨
94
  """
95
  )
96
 
97
+ # Upload image file and process image
 
98
  file = st.file_uploader("", type=["jpg", "png"])
99
 
100
+ if file is not None:
101
+ # Create two columns for the image and the captions
102
+ col1, col2 = st.columns(2)
103
+
104
+ with col1:
105
+ # Image column, left screen.
106
+ st.markdown("#### Photo:")
107
+ image = Image.open(file).convert('RGB')
108
+ image.thumbnail((400, 400))
109
+ st.image(image, caption='Uploaded Image')
110
+
111
+ with col2:
112
+ # Caption column, right screen.
113
+ predictions = import_and_predict(image)
114
+ st.markdown("#### Captions:")
115
+ st.write(predictions)
 
 
 
 
 
 
116
  else:
117
+ st.text("Please upload an image to generate captions.")