def makeJson(hash_id): if 'api' in session: api = session['api'] else: access_token = redis_server.get(hash_id) api = InstagramAPI(access_token=access_token) liked = api.user_liked_media(count=-1) user_id = api.user().id #print liked dumpcontent = [] for i in liked[0]: tmpdict = {} if i.caption: tmpdict["description"] = "<img src='%s' title='%s'/>" % (i.images['standard_resolution'].url, i.caption.text) tmpdict["title"] = i.caption.text else: tmpdict["description"] = "<img src='%s' title=''/>" % (i.images['standard_resolution'].url) tmpdict["title"] = '' tmpdict["link"] = i.images['standard_resolution'].url dumpcontent.append(tmpdict) opendump = json.dumps(dumpcontent) response = make_response(str(opendump)) response.headers['Content-Type'] = 'application/json' return response
def makeRss(hash_id): if 'api' in session: api = session['api'] else: access_token = redis_server.get(hash_id) api = InstagramAPI(access_token=access_token) liked = api.user_liked_media(count=-1) username = api.user().username user_id = api.user().id items = [] for i in liked[0]: if i.caption: title = i.caption.text else: title='' link = i.images['standard_resolution'].url description = "<img src='%s' title='%s'/>" % (link, title) item = PyRSS2Gen.RSSItem(title,link,description) items.append(item) title = "%s's Instamator RSS Feed" % username link = "http://instamator.ep.io/%s/rss" % hash_id rss = PyRSS2Gen.RSS2( title= title, description ='', link=link, items=items, ) rss_response = rss.to_xml() response = make_response(rss_response) response.headers['Content-Type'] = 'application/rss+xml' return response
def update_user_likes(download): api = InstagramAPI(access_token=settings.INSTAGRAM_ACCESS_TOKEN.decode(), client_secret=settings.INSTAGRAM_CLIENT_SECRET.decode()) # Figure out the logged in user user = api.user() username = user.username # Find the media the user has liked liked_media, next = api.user_liked_media() update_likes(user=username, photos=liked_media, download=download)
def update_user_likes(download): api = InstagramAPI( access_token=settings.INSTAGRAM_ACCESS_TOKEN, client_secret=settings.INSTAGRAM_CLIENT_SECRET) # Figure out the logged in user user = api.user() username = user.username # Find the media the user has liked liked_media, next = api.user_liked_media() update_likes(user=username, photos=liked_media, download=download)
def User_Liked_Media(page=1): u = InstagramAPI(access_token=session['access_token'], client_secret=secrets['client_secret']) liked_media, next_ = u.user_liked_media() for i in range(1, page): liked_media, next_ = u.user_liked_media(count=20, with_next_url=next_) photos_thumbnail = [] photos_standard = [] title = "User Liked Media-Page " + str(page) prev_page = False next_page = False if next_: prev_page = True if page != 1: next_page = True for media in liked_media: photos_thumbnail.append("{}".format(media.images['thumbnail'].url)) photos_standard.append("{}".format(media.images['standard_resolution'] .url)) return render_template("recent.html", thumb=photos_thumbnail, photos=photos_standard, prev=prev_page, next=next_page, page=page, title=title)
def makeText(hash_id): '''Makes Text file about Instagram likes hash_id: unique id for user ''' if 'api' in session: api = session['api'] else: access_token = redis_server.get(hash_id) api = InstagramAPI(access_token=access_token) liked = api.user_liked_media(count = -1) user_id = api.user().id textcontent = [] for i in liked[0]: textcontent.append(i.images['standard_resolution'].url) text_response = "\n".join(textcontent) response = make_response(text_response) response.headers['Content-Type'] = 'text/plain' return response
def display_user(usernm,page=1): show_user = sessionn.query(User).filter_by(user_name=usernm).first() if show_user and show_user.first_login==1: # show_media = models.Images.query.filter_by(user_id=show_user.un_id).paginate(1,3,False).items show_media_pagination = sessionn.query(Images).filter_by(user_id=show_user.un_id).order_by(Images.created_time.desc()) show_media = sessionn.query(Images).filter_by(user_id=show_user.un_id).all() paginated_show_media = paginate(show_media_pagination, page,POSTS_PER_PAGE,False) liked_media=[] my_likes=0 # print session['instagram_access_token_likes'] if request.method == 'POST': f=request.form if f['bttn']=='Featured': my_likes=0 else: my_likes=1 if my_likes==1: if 'instagram_access_token_likes' in session and 'instagram_user_likes' in session: userAPI = InstagramAPI(access_token=session['instagram_access_token_likes']) liked_media, next = userAPI.user_liked_media() show_liked=[] # if img1 in liked_media: if len(liked_media)>0 and len(show_media)>0: for img1 in liked_media: for obj in show_media: # print "Liked images ke URL" # print photo_id_from_url(img1.likes[0]) #img1.likes[0] # print "show_media ke URL" # print photo_id_from_url(obj.img_url) #obj.img_url liked_photo = photo_id_from_url(img1.likes[0]) all_photo = photo_id_from_url(obj.img_url) if liked_photo == all_photo: show_liked.append(obj) return render_template("buy_product.html",usernm=usernm, my_likes=my_likes, show_user=show_user, liked_media=show_liked, show_media=paginated_show_media) else: return "Not registered Company"
def search(username, access_token): #user_q = User.query.filter_by(nickname = username).first() #if user_q: # api = InstagramAPI(access_token=user_q.access_token) #else: # file_with_token = open('app/access_token', "r") # access_token = file_with_token.readline().split()[0] api = InstagramAPI(access_token=access_token) user_id = [] for user in api.user_search(q=username): if user.username == username: user_id = [user] #print user_id #print type(user_id) #print 'OK_TEST_1' if user_id: recent_media, next_ = api.user_recent_media(user_id=str(user_id[0].id), count=11) liked = api.user_liked_media(user_id=str(user_id[0].id)) liked = liked[:-1] user_liked = {} for media in liked[0]: if 'user' in dir(media): if media.user.username in user_liked: user_liked[media.user.username] += 1 else: user_liked[media.user.username] = 1 user_liked_sorted = [] for pair in reversed(sorted(user_liked.items(), key=lambda item: item[1])): user_liked_sorted.append([pair[0], pair[1]]) locations = {} for feed in recent_media: if 'location' in dir(feed): loc = feed.location.name.lower() if loc: if loc in locations: locations[loc] += 1 else: locations[loc] = 1 locations_sorted = [] for pair in reversed(sorted(locations.items(), key=lambda item: item[1])): locations_sorted.append([pair[0], pair[1]]) tags = {} for feed in recent_media: if 'tags' in dir(feed): for tag in feed.tags: key = tag.name.lower() if key in tags: tags[key] +=1 else: tags[key] = 1 tags_sorted = [] for pair in reversed(sorted(tags.items(), key=lambda item: item[1])): tags_sorted.append([pair[0], pair[1]]) captions = {} for feed in recent_media: if 'caption' in dir(feed): if 'text' in dir(feed.caption): caption = feed.caption.text.lower() + ' ' word = "" for symb in caption: if (ord(symb) == ord('#')) or (ord(u'a') <= ord(symb) <= ord(u'z')) or (ord(u'а') <= ord(symb) <= ord(u'я')): word+=symb else: if word: if not (word[0] == '#'): if (ord(u'а') <= ord(word[0]) <= ord(u'я')): word = morph.parse(word)[0].normal_form type = morph.parse(word)[0].tag.POS if type == 'PREP' or type == 'CONJ' or type == 'PRCL' or type == 'INTJ' or type == 'NUMR' or type == 'COMP': continue elif (ord(u'a') <= ord(word[0]) <= ord(u'z')): word = stemmer.stem(word) type = nltk.pos_tag(nltk.tokenize.word_tokenize(word))[0][1] if type == 'IN' or type == 'CC' or type == 'RB' or type == 'JJR': continue if word not in stopwords: if word in captions: captions[word]+=1 else: captions[word]=1 word = "" comments = [] comment_rating = {} for media in recent_media: for obj in media.comments: user_commented = unicode(obj.user.username) if user_commented in comment_rating: comment_rating[user_commented] += 1 else: comment_rating[user_commented] = 1 comment = obj.text.lower() + ' ' comments.append(obj.text) word = "" for symb in comment: if (ord(symb) == ord('@')) or (ord(symb) == ord('#')) or (ord(u'a') <= ord(symb) <= ord(u'z')) or (ord(u'а') <= ord(symb) <= ord(u'я')): word+=symb else: if word: if not ((word[0] == '#') or (word[0] == '@')): if (ord(u'а') <= ord(word[0]) <= ord(u'я')): word = morph.parse(word)[0].normal_form type = morph.parse(word)[0].tag.POS if type == 'PREP' or type == 'CONJ' or type == 'PRCL' or type == 'INTJ' or type == 'NUMR' or type == 'COMP': continue elif (ord(u'a') <= ord(word[0]) <= ord(u'z')): word = stemmer.stem(word) type = nltk.pos_tag(nltk.tokenize.word_tokenize(word))[0][1] if type == 'IN' or type == 'CC' or type == 'RB' or type == 'JJR': continue if word not in stopwords: if word in captions: captions[word]+=1 else: captions[word]=1 word = "" captions_sorted = [] for pair in reversed(sorted(captions.items(), key=lambda item: item[1])): captions_sorted.append([pair[0], pair[1]]) comment_rating_sorted = [] for pair in reversed(sorted(comment_rating.items(), key=lambda item: item[1])): comment_rating_sorted.append([pair[0], pair[1]]) images = {} videos = [] filters = {} likes_of_users = {} count_of_all_likes = 0 for media in recent_media: if 'videos' not in dir(media) and 'images' in dir(media): if (media.images['standard_resolution'].url) in images: images[media.images['standard_resolution'].url] += media.like_count else: images[media.images['standard_resolution'].url] = media.like_count filter = unicode(media.filter) if filter in filters: filters[filter] += 1 else: filters[filter] = 1 if 'videos' in dir(media): videos.append(media.videos['standard_resolution'].url) for usr in media.likes: if usr.username in likes_of_users: likes_of_users[usr.username] += 1 else: likes_of_users[usr.username] = 1 count_of_all_likes+=media.like_count likes_of_users_sorted = [] for pair in reversed(sorted(likes_of_users.items(), key=lambda item: item[1])): likes_of_users_sorted.append([pair[0], pair[1]]) images_sorted = [] for pair in reversed(sorted(images.items(), key=lambda item: item[1])): images_sorted.append([pair[0], pair[1]]) filters_sorted = [] for pair in reversed(sorted(filters.items(), key=lambda item: item[1])): filters_sorted.append([pair[0], pair[1]]) user_bsc = api.user(user_id[0].id) basic_information = [user_bsc.id, user_bsc.full_name, user_bsc.website, user_bsc.counts["media"], count_of_all_likes, user_bsc.counts["follows"], user_bsc.counts["followed_by"], user_bsc.profile_picture, user_bsc.bio] #print "OK_TEST_2" return [basic_information, images_sorted, videos, captions_sorted, tags_sorted, locations_sorted, comments, user_liked_sorted, likes_of_users_sorted, comment_rating_sorted, filters_sorted] else: return [] # print "IMAGES" # for obj in images: # print obj # # print "VIDEOS" # for obj in videos: # print obj # # print "CAPTIONS:" # for obj in captions_sorted: # print obj[0], obj[1] # # print "HASHTAGS:" # for obj in tags_sorted: # print obj[0], obj[1] # # print "PLACES:" # for obj in locations_sorted: # print obj[0], obj[1] # # print "MOST POPULAR PLACES:" # mstpopular = locations_sorted[:3] # for obj in mstpopular: # print obj[0], obj[1]
def myRecentLikes(): #written by Tim content = "<h2>User's Recent Likes</h2>" access_token = request.session['access_token'] if not access_token: print "Missing Access Token" return 'Missing Access Token' try: api = InstagramAPI(access_token=access_token, client_secret=CONFIG['client_secret']) _user_id =(api.user()).id liked_media, next = api.user_liked_media(count=9) print "Webpage is loading...." counter = 0; photos = [] filters = [] usersThatLiked = [] content += "<div id='liked_media'>" content +="<style>figure{ width:33.3%; float:left; margin:0px; text-align:center; padding:0px;} </style>" for media in liked_media: content += "<figure>" filters.append(media.filter) usersThatLiked.extend(api.media_likes(media_id = media.id)) counter = counter +1 #photos.append('<div style="float:left;">') if(media.type == 'video'): content += ('<video controls width height="150"><source type="video/mp4" src="%s"/></video>' % (media.get_standard_resolution_url())) #photos.append('<video controls width height="150"><source type="video/mp4" src="%s"/></video>' % (media.get_standard_resolution_url())) else: content+= ("<img src=%s/>" % (media.get_low_resolution_url())) content+= ("<figcaption>@%s" % (media.user.username)) content+= "</figcaption>" #photos.append('<div class="floated_img"><img src="%s"/></div>' % (media.get_thumbnail_url())) content+="</figure>" content+= "</div><br>" filterCounter = Counter(filters) #makes a counter object based on the list of filters usersThatLikedCounter = Counter(usersThatLiked) #counts instances of any person liking the same pictures that the user did #outputs a ranked list of the filters used in the liked posts above content += "<h2> Filters used (count): </h2><ol>" for filterWithCount in filterCounter.most_common(): content += "<li>" + filterWithCount[0] +" ("+str(filterWithCount[1])+")</li>" content += "</ol>" #gets a list of people that our user follows (used to make accurate suggestions of people to follow) following_list, next_ = api.user_follows() #make a set of user id numbers following_ids = set() for user in following_list: following_ids.add(user.id) #outputs the most common users that liked the same media content += "<h2> Top users that also liked these posts: </h2><p>Below is a list of users who also liked the posts above, if you are not already following them, there will be a link.<ol>" for userWithCount in usersThatLikedCounter.most_common(11): if (userWithCount[0].id != _user_id): #makes sure that the current user is not displayed content += "<li>" + userWithCount[0].username +" ("+str(userWithCount[1])+" similar likes)" if(userWithCount[0].id not in following_ids): content += (" <a href='/user_follow/%s'>Follow</a>" % (userWithCount[0].id)) content += (" <p>Here's a link to their Instagram Profile:" ) content += (" <a href='https://www.instagram.com/%s'>instagram.com/%s</a></p></li>" % (userWithCount[0].username, userWithCount[0].username)) content += "</ol>" except Exception as e: print "in exception ..." print(e) return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)
from instagram.client import InstagramAPI access_token = "25290587.1677ed0.7131ff8507da447bb7fe54dab79fd273" client_secret = "a8545940747f4536873f06e4a60c23a4" api = InstagramAPI(access_token=access_token, client_secret=client_secret) recent_media, next_ = api.user_recent_media(user_id="259220806", count=1) for media in recent_media: print (media.caption.text) curMedia = str(media) curMedia = curMedia[7:] likesArr = api.media_likes(curMedia) print (likesArr) followersList = open('followersList.txt', 'w+') followers, next = api.user_followed_by(user_id="259220806") count = 0 while len(followers)<100: more_follows, next = api.user_followed_by(with_next_url=next) followers.extend(more_follows) count += 50 #strFollowers = [] #for name in followers: # strFollowers.append(str(name)[6:]) for name in followers: curMedia = api.user_liked_media() #user = api.user()
def find_friends(access_token): client_secret = "22a6a272eeaa4b18aba7b242ade48cd3" api = InstagramAPI(access_token=access_token, client_secret=client_secret) #sets recent_feed media recent_feed, next_ = api.user_recent_media(100) """ Finding users tagged in your photos, this should be the most important factor """ users = [] num_photos_in_feed = 0 num_photos_tagged = 0 for media in recent_feed: num_photos_in_feed += 1 if media.users_in_photo: for tagged_person in media.users_in_photo: num_photos_tagged += 1 users.append(tagged_person.user) tagged_user = {} for user in users: if user.id in tagged_user.keys(): tagged_user[user.id] += 1 else: tagged_user[user.id] = 1 #Done #likes - list of users that has liked each photo likes = [] for media in recent_feed: a = api.media_likes(media.id) for i in a: likes.append(i) # d_ids - dict key = user id and value is number of times they have liked a photo likes_ids = [user.id for user in likes] d_ids = {} for userid in likes_ids: d_ids[userid] = likes_ids.count(userid) #users is list of all users that you have liked a photo of theirs feed, next_ = api.user_liked_media(access_token=access_token, count = 100) users = [] for media in feed: users.append(media.user) #d - pairs users and number of times you have liked their photo other_ids = [user.id for user in users] d = {} for user in other_ids: d[user] = other_ids.count(user) #all relevant users like_users = {} for user in likes: like_users[user.id] = user liked_users = {} for user in users: liked_users[user.id] = user like_users.update(liked_users) all_users = list(like_users.values()) #give scores to each user scores = {} for user in all_users: score = 0 if user.id in d_ids: # d_ids - dict key = user id and value is number of times they have liked a photo score += 5 *d_ids[user.id] if user.id in d: score += 2 * d[user.id] #d - pairs users and number of times you have liked their photo if user.id in tagged_user: if (num_photos_tagged < 2) or ((num_photos_tagged/num_photos_in_feed) < .2): score += 14 * tagged_user[user.id] else: score += 13 * tagged_user[user.id] scores[user] = score #print(d) #print(d_ids) #gives scores for like_me index scores_likeme = {} for user in all_users: score = 0 if user.id in d_ids: score += d_ids[user.id] scores_likeme[user] = score final_likeme = [] for _ in range(5): v=list(scores_likeme.values()) k=list(scores_likeme.keys()) score = k[v.index(max(v))] final_likeme.append(score.full_name) scores_likeme.pop(score) final_likeme_str = str(final_likeme) #print(final_likeme, "diff") #gives scores for like_them index scores_likethem = {} for user in all_users: score = 0 if user.id in d: score += d[user.id] scores_likethem[user] = score final_likethem = [] for _ in range(5): v=list(scores_likethem.values()) k=list(scores_likethem.keys()) score = k[v.index(max(v))] final_likethem.append(score.full_name) scores_likethem.pop(score) final_likethem_str = str(final_likethem) #print(final_likethem, 'more diff') #compute final list of 5 best users with highest scores final = [] finalname = [] finalscore = [] for _ in range(5): v=list(scores.values()) k=list(scores.keys()) score = k[v.index(max(v))] final.append(score) finalname.append(score.full_name) finalscore.append(scores[score]) scores.pop(score) final_str = str(final) finalname_str = str(finalname) finalscore_str = str(finalscore) return final