kusumakar commited on
Commit
f0ea0b8
1 Parent(s): 24b6541

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +141 -0
  2. hashies.txt +1 -0
  3. requirements.txt +11 -0
app.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image
3
+ import numpy as np
4
+ import nltk
5
+ nltk.download('stopwords')
6
+ nltk.download('punkt')
7
+ import pandas as pd
8
+ import random
9
+ import easyocr
10
+ import re
11
+ from nltk.corpus import stopwords
12
+ from nltk.tokenize import word_tokenize
13
+ from sklearn.feature_extraction.text import TfidfVectorizer
14
+ from sklearn.metrics.pairwise import cosine_similarity
15
+ from transformers import AutoTokenizer, VisionEncoderDecoderModel, ViTFeatureExtractor
16
+ @st.cache(allow_output_mutation=True)
17
+
18
+ # Directory path to the saved model on Google Drive
19
+ model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
20
+
21
+ # Load the feature extractor and tokenizer
22
+ feature_extractor = ViTFeatureExtractor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
23
+ tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
24
+
25
+
26
+ def generate_captions(image):
27
+ generated_caption = tokenizer.decode(model.generate(feature_extractor(image, return_tensors="pt").pixel_values.to("cpu"))[0])
28
+ sentence = generated_caption
29
+ text_to_remove = "<|endoftext|>"
30
+ generated_caption = sentence.replace(text_to_remove, "")
31
+ return generated_caption
32
+
33
+ # use easyocr to extract text from the image
34
+ def image_text(image):
35
+ reader = easyocr.Reader(['en'])
36
+ text = reader.readtext(np.array(image))
37
+ detected_text = " ".join([item[1] for item in text])
38
+
39
+ # Extract individual words, convert to lowercase, and add "#" symbol
40
+ detected_text= ['#' + entry[1].strip().lower().replace(" ", "_") for entry in text]
41
+ return detected_text
42
+
43
+ # Load NLTK stopwords for filtering
44
+ stop_words = set(stopwords.words('english'))
45
+
46
+ # Add hashtags to keywords, which have been generated from image captioing
47
+ def add_hashtags(keywords):
48
+ hashtags = []
49
+
50
+ for keyword in keywords:
51
+ # Generate hashtag from the keyword (you can modify this part as per your requirements)
52
+ hashtag = '#' + keyword.lower()
53
+
54
+ hashtags.append(hashtag)
55
+
56
+ return hashtags
57
+
58
+ def trending_hashtags():
59
+ # Read trending hashtags from a file separated by commas
60
+ with open("hashies.txt", "r") as file:
61
+ hashtags_string = file.read()
62
+
63
+ # Split the hashtags by commas and remove any leading/trailing spaces
64
+ trending_hashtags = [hashtag.strip() for hashtag in hashtags_string.split(',')]
65
+
66
+ # Create a DataFrame from the hashtags
67
+ df = pd.DataFrame(trending_hashtags, columns=["Hashtags"])
68
+
69
+ # Function to extract keywords from a given text
70
+ def extract_keywords(text):
71
+ tokens = word_tokenize(text)
72
+ keywords = [token.lower() for token in tokens if token.lower() not in stop_words]
73
+ return keywords
74
+
75
+ # Extract keywords from caption and trending hashtags
76
+ caption_keywords = extract_keywords(caption)
77
+ hashtag_keywords = [extract_keywords(hashtag) for hashtag in df["Hashtags"]]
78
+
79
+ # Function to calculate cosine similarity between two strings
80
+ def calculate_similarity(text1, text2):
81
+ tfidf_vectorizer = TfidfVectorizer()
82
+ tfidf_matrix = tfidf_vectorizer.fit_transform([text1, text2])
83
+ similarity_matrix = cosine_similarity(tfidf_matrix[0], tfidf_matrix[1])
84
+ return similarity_matrix[0][0]
85
+
86
+ # Calculate similarity between caption and each trending hashtag
87
+ similarities = [calculate_similarity(' '.join(caption_keywords), ' '.join(keywords)) for keywords in hashtag_keywords]
88
+
89
+ # Sort trending hashtags based on similarity in descending order
90
+ sorted_hashtags = [hashtag for _, hashtag in sorted(zip(similarities, df["Hashtags"]), reverse=True)]
91
+
92
+ # Select top k relevant hashtags (e.g., top 5) without duplicates
93
+ selected_hashtags = list(set(sorted_hashtags[:5]))
94
+
95
+ selected_hashtag = [word.strip("'") for word in selected_hashtags]
96
+
97
+ return selected_hashtag
98
+
99
+ # create the Streamlit app
100
+ def app():
101
+ st.title('Iamge from your Side, Trending Hashtags from our Site')
102
+
103
+ st.write('Upload an image to see what we have in store, Alwyas For You!')
104
+
105
+ # create file uploader
106
+ uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
107
+
108
+ # check if file has been uploaded
109
+ if uploaded_file is not None:
110
+ # load the image
111
+ image = Image.open(uploaded_file)
112
+
113
+ # Image Captions
114
+ string = generate_captions(uploaded_file)
115
+ tokens = word_tokenize(string)
116
+ keywords = [token.lower() for token in tokens if token.lower() not in stop_words]
117
+ hashtags = add_hashtags(keywords)
118
+
119
+ # Text Captions from image
120
+ in_image_text = image_text(uploaded_file)
121
+
122
+ #Final Hashtags Generation
123
+ web_hashtags = trending_hashtags()
124
+
125
+ combined_hashtags = hashtags + in_image_text + web_hashtags
126
+
127
+ # Shuffle the list randomly
128
+ random.shuffle(combined_hashtags)
129
+
130
+ combined_hashtags = list(set(item for item in combined_hashtags[:15] if not re.search(r'\d$', item)))
131
+
132
+
133
+ # display the image
134
+ st.image(image, width=500, height=400)
135
+ st.write("Here it is THE CAPTIONS Just! for your Photo",string)
136
+ st.write("ohh! finally we have decided these are the best ",combined_hashtags)
137
+
138
+ # run the app
139
+ if __name__ == '__main__':
140
+ app()
141
+
hashies.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ '#instagood','#sand','#surfboard ','#love', '#photography', '#instagram', '#photooftheday', '#india', '#picoftheday', '#nature', '#instadaily', '#likeforlikes', '#follow', '#fashion', '#travel', '#followforfollowback', '#kerala', '#beautiful', '#style', '#art', '#travelphotography', '#followme', '#model', '#naturephotography', '#photo', '#smile', '#instalike', '#happy', '#bhfyp', '#like', '#life', '#stayhome', '#mumbai', '#cute', '#photoshoot', '#photographer', '#friends', '#me', '#instamood', '#food', '#likeforfollow', '#travelgram', '#lifestyle', '#keralagram', '#insta', '#trending', '#beauty', '#fun', '#like4like', '#igers', '#tiktok', '#like4likes', '#sunset', '#incredibleindia', '#throwback', '#girl', '#staysafe', '#keralatourism', '#likeforlike', '#bestoftheday', '#fashionblogger', '#kochi', '#quarantine', '#sky', '#portrait', '#wanderlust', '#keralagodsowncountry', '#tbt', '#likes', '#instafashion', '#instapic', '#followers', '#mobilephotography', '#music', '#fitness', '#mallu', '#delhi', '#swag', '#photographers_of_india', '#amazing', '#motivation', '#follow4follow', '#explore', '#godsowncountry', '#summer', '#followforfollow', '#modeling', '#loveyourself', '#indianphotography', '#indian', '#mountains', '#landscape', '#look', '#likesforlike', '#goodvibes', '#streetphotography', '#lockdown', '#travelblogger', '#selfie', '#malayalam', '#comment','#nyc', '#dogsofinstagram', '#california', '#cell', '#phone', '#newyork', '#losangeles', '#miami', '#family', '#florida', '#beach', '#foodie', '#adventure', '#explorepage', '#hiking', '#dog', '#foodporn', '#2020', '#makeup', '#socialdistancing', '#artist', '#newyorkcity', '#realestate', '#design', '#puppy', '#covid19', '#ootd', '#blacklivesmatter', '#roadtrip', '#interiordesign', '#outdoors', '#repost', '#blessed', '#colorado', '#vacation', '#texas', '#chicago', '#coronavirus', '#puppiesofinstagram', '#inspiration', '#quarantinelife', '#home', '#puppylove', '#flowers', '#dogstagram', '#nofilter', '#selfcare', '#selflove', '#sandiego', '#getoutside', '#fitnessmotivation', '#entrepreneur', '#smallbusiness', '#dogs', '#france', '#paris', '#sun', '#confinement', '#weekend', '#instamoment', '#sea', '#holidays', '#architecture', '#southoffrance', '#picture', '#vacances', '#marseille', '#igersfrance', '#bretagne', '#mood', '#lyon', '#frenchgirl', '#soleil', '#blackandwhite', '#cotedazur', '#provence', '#amour', '#frenchriviera', '#sunnyday', '#french', '#paysage', '#bordeaux', '#view', '#sport', '#europe', '#plage', '#naturelovers', '#instafood', '#instatravel', '#shooting', '#photographie', '#summervibes', '#nice', '#parisienne', '#trip', '#landscapephotography', '#outfit', '#blue', '#pictureoftheday', '#parisfrance', '#maldives', '#maldivesislands', '#ocean', '#paradise', '#holiday', '#indianocean', '#island','#islandlife', '#traveltheworld', '#maldivesresorts', '#beautifuldestinations', '#beachlife', '#traveling', '#travelling', '#honeymoon', '#maldiveslovers', '#luxurylifestyle', '#luxury', '#maldive', '#traveler', '#malediven', '#traveller', '#beautifulmaldives', '#luxurytravel', '#memories', '#maldivas', '#diving', '#scubadiving', '#tropical', '#relax', '#beachvibes', '#maldivesisland', '#underwaterphotography', '#sunnysideoflife', '#underwater', '#traveladdict', '#couplegoals', '#maldivesmania', '#resort', '#travelblog', '#maldivesinsider', '#clouds', '#sand'
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit==0.88.0
2
+ Pillow==8.4.0
3
+ numpy==1.21.4
4
+ nltk==3.6.5
5
+ pandas==1.3.4
6
+ easyocr==1.4
7
+ scikit-learn==0.24.2
8
+ torch==1.9.0
9
+ transformers==4.11.3
10
+ altair<5
11
+ click<8.0