Exemplo n.º 1
0
def index(req, session, postgres_handle):

    root_user = None
    if 'user_id' in req.params:
        root_user = TwitterUser.get_by_id(req.params['user_id'],
                                          postgres_handle)
    if not root_user:
        root_user = TwitterUser.by_screen_name('SmartTypes', postgres_handle)

    reduction = TwitterReduction.get_latest_reduction(root_user.id,
                                                      postgres_handle)
    if not reduction:
        root_user = TwitterUser.by_screen_name('SmartTypes', postgres_handle)
        reduction = TwitterReduction.get_latest_reduction(
            root_user.id, postgres_handle)

    return {
        'active_tab':
        'social_map',
        'template_path':
        'social_map/index.html',
        'root_user':
        root_user,
        'reduction':
        reduction,
        'num_groups':
        len(TwitterGroup.all_groups(reduction.id, postgres_handle)),
        'users_with_a_reduction':
        TwitterReduction.get_users_with_a_reduction(postgres_handle),
    }
Exemplo n.º 2
0
def index(req, session, postgres_handle):
    #if it's not a valid request keep reduction_id None
    #don't do work for bots that don't know what they're
    #looking for
    reduction = None
    user_reduction_counts = TwitterReduction.get_user_reduction_counts(
        postgres_handle)
    random.shuffle(user_reduction_counts)

    if req.path.split('/') > 1 and req.path.split(
            '/')[1]:  # path looks like '/something'
        root_user = TwitterUser.by_screen_name(
            req.path.split('/')[1], postgres_handle)
        if root_user:
            reduction = TwitterReduction.get_latest_reduction(
                root_user.id, postgres_handle)
        if not reduction and is_int(req.path.split('/')[1]):
            reduction = TwitterReduction.get_by_id(
                req.path.split('/')[1], postgres_handle)
    else:
        reduction = TwitterReduction.get_latest_reduction(
            user_reduction_counts[0][0].id, postgres_handle)

    return {
        'reduction_id':
        reduction.id
        if reduction and reduction.tiles_are_written_to_disk else None,
        'reduction':
        reduction
        if reduction and reduction.tiles_are_written_to_disk else None,
        'user_reduction_counts':
        user_reduction_counts
    }
Exemplo n.º 3
0
def logged_in_user(request):
    
    screen_name = request.params['screen_name']
    logged_in_user = TwitterUser.by_screen_name(screen_name)
    return {
        'logged_in_user':logged_in_user,
        'TwitterGroup':TwitterGroup,
    }
Exemplo n.º 4
0
def index(req, session, postgres_handle):
    root_user = None
    if 'user_id' in req.params:
        root_user = TwitterUser.get_by_id(req.params['user_id'], postgres_handle)
    if not root_user:
        root_user = TwitterUser.by_screen_name('SmartTypes', postgres_handle)
    reduction = TwitterReduction.get_latest_reduction(root_user.id, postgres_handle)
    if not reduction:
        root_user = TwitterUser.by_screen_name('SmartTypes', postgres_handle)
        reduction = TwitterReduction.get_latest_reduction(root_user.id, postgres_handle)
    return {
        'active_tab': 'social_map',
        'template_path': 'social_map/index.html',
        'root_user': root_user,
        'reduction': reduction,
        'num_groups': len(TwitterGroup.all_groups(reduction.id, postgres_handle)),
        'users_with_a_reduction': TwitterReduction.get_users_with_a_reduction(postgres_handle),
    }
Exemplo n.º 5
0
def community_features(req, session, postgres_handle):
    reduction = None
    if req.path.split('/') > 3 and req.path.split('/')[3]:  # path looks like '/social_map/community_features/something'
        root_user = TwitterUser.by_screen_name(req.path.split('/')[3], postgres_handle)
        if root_user:
            reduction = TwitterReduction.get_latest_reduction(root_user.id, postgres_handle)
        if not reduction and is_int(req.path.split('/')[3]):
            reduction = TwitterReduction.get_by_id(req.path.split('/')[3], postgres_handle)
    return {
        'content_type': 'application/json',
        'json':reduction.get_geojson_community_features() if reduction else [],
    }
Exemplo n.º 6
0
def user(request):
    
    if 'user_id' in request.params:
        user_id = int(request.params['user_id'])
        twitter_user = TwitterUser.get_by_id(user_id)
    else:
        screen_name = request.params['screen_name']
        twitter_user = TwitterUser.by_screen_name(screen_name)
    
    return {
        'twitter_user':twitter_user,
    }
Exemplo n.º 7
0
def load_user_and_the_people_they_follow(api_handle, screen_name):
    print "Attempting to load %s" % screen_name
    continue_or_exit(api_handle)
    
    try:    
        api_user = api_handle.get_user(screen_name=screen_name)
    except TweepError, ex:
        print "Got a TweepError: %s." % ex  
        if str(ex) == "Not found":
            print "Setting caused_an_error for %s " % screen_name
            model_user = TwitterUser.by_screen_name(screen_name)
            model_user.caused_an_error = datetime.now()
            model_user.save()
            return model_user
Exemplo n.º 8
0
def load_network_from_the_db(postgres_handle, distance):
  network = OrderedDict()
  def add_user_to_network(user):
    network[user.id] = {}
    network[user.id]['following_ids'] = set(user.following_ids)
    #network[user.id]['following_ids'].add(user.id)
    network[user.id]['follower_ids'] = set([])
    network[user.id]['following_count'] = user.following_count
    network[user.id]['followers_count'] = user.followers_count
  twitter_user = TwitterUser.by_screen_name('SmartTypes', postgres_handle)
  add_user_to_network(twitter_user)
  for following in twitter_user.following:
    add_user_to_network(following)
    for following_following in following.following[:distance]:
      add_user_to_network(following_following)
  return network
Exemplo n.º 9
0
def load_network_from_the_db(postgres_handle, distance):
    network = OrderedDict()

    def add_user_to_network(user):
        network[user.id] = {}
        network[user.id]['following_ids'] = set(user.following_ids)
        network[user.id]['follower_ids'] = set([])
        network[user.id]['following_count'] = user.following_count
        network[user.id]['followers_count'] = user.followers_count

    twitter_user = TwitterUser.by_screen_name('SmartTypes', postgres_handle)
    add_user_to_network(twitter_user)
    for following in twitter_user.following:
        add_user_to_network(following)
        for following_following in following.following[:distance]:
            add_user_to_network(following_following)
    return network
Exemplo n.º 10
0
def index(req, session, postgres_handle):
    #if it's not a valid request keep reduction_id None
    #don't do work for bots that don't know what they're 
    #looking for
    reduction = None
    user_reduction_counts = TwitterReduction.get_user_reduction_counts(postgres_handle)
    random.shuffle(user_reduction_counts)

    if req.path.split('/') > 1 and req.path.split('/')[1]:  # path looks like '/something'
        root_user = TwitterUser.by_screen_name(req.path.split('/')[1], postgres_handle)
        if root_user:
            reduction = TwitterReduction.get_latest_reduction(root_user.id, postgres_handle)
        if not reduction and is_int(req.path.split('/')[1]):
            reduction = TwitterReduction.get_by_id(req.path.split('/')[1], postgres_handle)
    else:
        reduction = TwitterReduction.get_latest_reduction(user_reduction_counts[0][0].id, postgres_handle)

    return {
        'reduction_id': reduction.id if reduction and reduction.tiles_are_written_to_disk else None,
        'reduction': reduction if reduction and reduction.tiles_are_written_to_disk else None,
        'user_reduction_counts': user_reduction_counts
    }
Exemplo n.º 11
0
            print "done"
        
            return False
        
        #dont forget this
        return True
            
    
if __name__ == "__main__":

    if not len(sys.argv) > 1:
        args_dict = {'screen_name':'SmartTypes'}
    else:
        args_dict = eval(sys.argv[1])
    screen_name = args_dict['screen_name']
    twitter_user = TwitterUser.by_screen_name(screen_name)
    
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)

    monitor_these_user_ids = twitter_user.following_following_ids[:4000]
    print "Num of users to monitor: %s" % len(monitor_these_user_ids)
    listener = Listener(monitor_these_user_ids)
    stream = Stream(auth,listener)

    stream.filter(follow=monitor_these_user_ids)




Exemplo n.º 12
0
        vertex_order_by=('size', True), edge_color="white", edge_width=0, edge_arrow_size=0.1, 
        edge_arrow_width=0.1)

if __name__ == "__main__":

    #call like this:
    #python reduce_graph.py SmartTypes 0
    start_time = datetime.now()
    postgres_handle = PostgresHandle(smarttypes.connection_string)

    if len(sys.argv) < 3:
        raise Exception('Need a twitter handle and distance.')
    else:
        screen_name = sys.argv[1]
        distance = int(sys.argv[2])
    root_user = TwitterUser.by_screen_name(screen_name, postgres_handle)

    smarttypes.config.IS_PROD = False
    if distance < 1:
        smarttypes.config.IS_PROD = True
        distance = 10000 / len(root_user.following[:1000])

    network = TwitterUser.get_rooted_network(root_user, postgres_handle, distance=distance)
    g = get_igraph_graph(network)
    layout_list = reduce_with_linloglayout(g, root_user)
    
    #id_communities
    g, community_idx_list, vertex_clustering = id_communities(g, layout_list, eps=0.62, min_samples=12)

    #set color based on communities
    color_array = np.array(community_idx_list)
            string.ljust(creds_username, 20),
            string.ljust(root_username, 20), 
            string.ljust(creds.email if creds.email else '', 30)
        )

if __name__ == "__main__":

    """
    if no args, show all creds
    if args, first arg is creds_username, second is root_username
    """
    if len(sys.argv) == 1:
        list_cred_details()

    elif len(sys.argv) == 2:
        creds_user = TwitterUser.by_screen_name(sys.argv[1], postgres_handle)
        creds = TwitterCredentials.get_by_twitter_id(creds_user.id, postgres_handle)
        creds.root_user_id = None
        creds.save()
        postgres_handle.connection.commit()

    else:
        creds_user = TwitterUser.by_screen_name(sys.argv[1], postgres_handle)
        root_user = TwitterUser.by_screen_name(sys.argv[2], postgres_handle)
        if not root_user:
            api_user = creds_user.credentials.api_handle.get_user(screen_name=sys.argv[2])
            root_user = TwitterUser.upsert_from_api_user(api_user, postgres_handle)
            postgres_handle.connection.commit()
        creds = TwitterCredentials.get_by_twitter_id(creds_user.id, postgres_handle)
        creds.root_user_id = root_user.id
        creds.save()
Exemplo n.º 14
0
def reduce_graph(screen_name, distance=20, min_followers=60):

    postgres_handle = PostgresHandle(smarttypes.connection_string)

    ###########################################
    ##reduce
    ###########################################
    root_user = TwitterUser.by_screen_name(screen_name, postgres_handle)
    follower_followies_map = root_user.get_graph_info(distance=distance, 
        min_followers=min_followers)
    gr = GraphReduce(screen_name, follower_followies_map)
    gr.reduce_with_linloglayout()

    ###########################################
    ##save reduction in db
    ###########################################
    root_user_id = root_user.id
    user_ids = []
    x_coordinates = []
    y_coordinates = []
    in_links = []
    out_links = []
    for i in range(len(gr.layout_ids)):
        user_id = gr.layout_ids[i]
        user_ids.append(user_id)
        x_coordinates.append(gr.reduction[i][0])
        y_coordinates.append(gr.reduction[i][1])
        itr_in_links = PostgresHandle.spliter.join(gr.G.predecessors(user_id))
        itr_out_links = PostgresHandle.spliter.join(gr.G.successors(user_id))
        in_links.append(itr_in_links)
        out_links.append(itr_out_links)
    twitter_reduction = TwitterReduction.create_reduction(root_user_id, user_ids,
        x_coordinates, y_coordinates, in_links, out_links, postgres_handle)
    postgres_handle.connection.commit()

    ###########################################
    ##save groups in db
    ###########################################
    groups = []
    for i in range(gr.n_groups):
        user_ids = []
        for j in range(len(gr.layout_ids)):
            if i == gr.groups[j]:
                user_ids.append(gr.layout_ids[j])
        #run pagerank to get the scores
        group_graph = networkx.DiGraph()
        group_edges = []
        for user_id in user_ids:
            for following_id in set(user_ids).intersection(follower_followies_map[user_id]):
                group_edges.append((user_id, following_id))
        print len(user_ids), len(group_edges)
        if not group_edges:
            continue
        group_graph.add_edges_from(group_edges)
        pagerank = networkx.pagerank(group_graph, max_iter=500)
        scores = []
        for user_id in user_ids:
            scores.append(pagerank.get(user_id, 0))
        groups.append(TwitterGroup.create_group(twitter_reduction.id, i, user_ids, scores,
            postgres_handle))
    postgres_handle.connection.commit()

    ###########################################
    ##makes for quicker queries in some cases
    ###########################################
    twitter_reduction.save_group_info(postgres_handle)
    postgres_handle.connection.commit()

    ###########################################
    ##mk_tag_clouds
    ###########################################
    TwitterGroup.mk_tag_clouds(twitter_reduction.id, postgres_handle)
    postgres_handle.connection.commit()
Exemplo n.º 15
0
def reduce_graph(screen_name, distance=20, min_followers=60):

    postgres_handle = PostgresHandle(smarttypes.connection_string)

    ###########################################
    ##reduce
    ###########################################
    root_user = TwitterUser.by_screen_name(screen_name, postgres_handle)
    follower_followies_map = root_user.get_graph_info(
        distance=distance, min_followers=min_followers)
    gr = GraphReduce(screen_name, follower_followies_map)
    gr.reduce_with_linloglayout()

    ###########################################
    ##save reduction in db
    ###########################################
    root_user_id = root_user.id
    user_ids = []
    x_coordinates = []
    y_coordinates = []
    in_links = []
    out_links = []
    for i in range(len(gr.layout_ids)):
        user_id = gr.layout_ids[i]
        user_ids.append(user_id)
        x_coordinates.append(gr.reduction[i][0])
        y_coordinates.append(gr.reduction[i][1])
        itr_in_links = PostgresHandle.spliter.join(gr.G.predecessors(user_id))
        itr_out_links = PostgresHandle.spliter.join(gr.G.successors(user_id))
        in_links.append(itr_in_links)
        out_links.append(itr_out_links)
    twitter_reduction = TwitterReduction.create_reduction(
        root_user_id, user_ids, x_coordinates, y_coordinates, in_links,
        out_links, postgres_handle)
    postgres_handle.connection.commit()

    ###########################################
    ##save groups in db
    ###########################################
    groups = []
    for i in range(gr.n_groups):
        user_ids = []
        for j in range(len(gr.layout_ids)):
            if i == gr.groups[j]:
                user_ids.append(gr.layout_ids[j])
        #run pagerank to get the scores
        group_graph = networkx.DiGraph()
        group_edges = []
        for user_id in user_ids:
            for following_id in set(user_ids).intersection(
                    follower_followies_map[user_id]):
                group_edges.append((user_id, following_id))
        print len(user_ids), len(group_edges)
        if not group_edges:
            continue
        group_graph.add_edges_from(group_edges)
        pagerank = networkx.pagerank(group_graph, max_iter=500)
        scores = []
        for user_id in user_ids:
            scores.append(pagerank.get(user_id, 0))
        groups.append(
            TwitterGroup.create_group(twitter_reduction.id, i, user_ids,
                                      scores, postgres_handle))
    postgres_handle.connection.commit()

    ###########################################
    ##makes for quicker queries in some cases
    ###########################################
    twitter_reduction.save_group_info(postgres_handle)
    postgres_handle.connection.commit()

    ###########################################
    ##mk_tag_clouds
    ###########################################
    TwitterGroup.mk_tag_clouds(twitter_reduction.id, postgres_handle)
    postgres_handle.connection.commit()
Exemplo n.º 16
0
import os
import pickle
from datetime import datetime
import numpy as np

import smarttypes, random
from smarttypes.utils.postgres_handle import PostgresHandle
postgres_handle = PostgresHandle(smarttypes.connection_string)

from smarttypes.model.twitter_credentials import TwitterCredentials
from smarttypes.model.twitter_user import TwitterUser
from smarttypes.model.twitter_reduction import TwitterReduction
from smarttypes.model.twitter_reduction_user import TwitterReductionUser
from smarttypes.model.twitter_community import TwitterCommunity


model_user = TwitterUser.by_screen_name('SmartTypes', postgres_handle)
api_handle = model_user.credentials.api_handle
api_user = api_handle.get_user(screen_name='SmartTypes')


Exemplo n.º 17
0
import os
import pickle
from datetime import datetime
import numpy as np

import smarttypes, random
from smarttypes.utils.postgres_handle import PostgresHandle
postgres_handle = PostgresHandle(smarttypes.connection_string)

from smarttypes.model.twitter_credentials import TwitterCredentials
from smarttypes.model.twitter_user import TwitterUser
from smarttypes.model.twitter_reduction import TwitterReduction
from smarttypes.model.twitter_reduction_user import TwitterReductionUser
from smarttypes.model.twitter_community import TwitterCommunity

model_user = TwitterUser.by_screen_name('SmartTypes', postgres_handle)
api_handle = model_user.credentials.api_handle
api_user = api_handle.get_user(screen_name='SmartTypes')
Exemplo n.º 18
0
def reduce_graph(screen_name,
                 distance=20,
                 min_followers=60,
                 pickle_it=True,
                 just_load_from_file=False):

    postgres_handle = PostgresHandle(smarttypes.connection_string)

    # if just_load_from_file:
    #     print "Loading data from a pickle."
    #     gr = GraphReduce(screen_name, {})
    #     f = open(gr.pickle_file_path)
    #     twitter_reduction, groups = pickle.load(f)
    #     twitter_reduction.id = None
    #     twitter_reduction.postgres_handle = postgres_handle
    #     twitter_reduction.save()
    #     postgres_handle.connection.commit()
    #     for group in groups:
    #         group.id = None
    #         group.reduction_id = twitter_reduction.id
    #         group.postgres_handle = postgres_handle
    #         group.save()
    #         postgres_handle.connection.commit()
    #     TwitterGroup.mk_tag_clouds(twitter_reduction.id, postgres_handle)
    #     postgres_handle.connection.commit()
    #     print "All done!"
    #     return 0

    ########################
    ##reduce
    ########################
    root_user = TwitterUser.by_screen_name(screen_name, postgres_handle)
    follower_followies_map = root_user.get_graph_info(
        distance=distance, min_followers=min_followers)
    gr = GraphReduce(screen_name, follower_followies_map)
    #gr.reduce_with_exafmm()
    gr.reduce_with_linloglayout()

    ########################
    ##save reduction in db
    ########################
    root_user_id = root_user.id
    user_ids = []
    x_coordinates = []
    y_coordinates = []
    in_links = []
    out_links = []
    for i in range(len(gr.layout_ids)):
        user_id = gr.layout_ids[i]
        user_ids.append(user_id)
        x_coordinates.append(gr.reduction[i][0])
        y_coordinates.append(gr.reduction[i][1])
        itr_in_links = PostgresHandle.spliter.join(gr.G.predecessors(user_id))
        itr_out_links = PostgresHandle.spliter.join(gr.G.successors(user_id))
        in_links.append(itr_in_links)
        out_links.append(itr_out_links)
    twitter_reduction = TwitterReduction.create_reduction(
        root_user_id, user_ids, x_coordinates, y_coordinates, in_links,
        out_links, postgres_handle)
    postgres_handle.connection.commit()

    ########################
    ##save groups in db
    ########################
    groups = []
    for i in range(gr.n_clusters):
        user_ids = []
        for j in range(len(gr.layout_ids)):
            if gr.layout_clusters[j][i] > 0:
                user_ids.append(gr.layout_ids[j])
        #run pagerank to get the scores
        group_graph = networkx.DiGraph()
        group_edges = []
        for user_id in user_ids:
            if user_id in follower_followies_map:
                for following_id in set(user_ids).intersection(
                        follower_followies_map[user_id]):
                    group_edges.append((user_id, following_id))
        print len(user_ids), len(group_edges)
        if not group_edges:
            continue
        group_graph.add_edges_from(group_edges)
        pagerank = networkx.pagerank(group_graph, max_iter=500)
        scores = []
        for user_id in user_ids:
            scores.append(pagerank.get(user_id, 0))
        groups.append(
            TwitterGroup.create_group(twitter_reduction.id, i, user_ids,
                                      scores, postgres_handle))
    postgres_handle.connection.commit()

    twitter_reduction.save_group_info(postgres_handle)
    postgres_handle.connection.commit()

    ########################
    ##mk_tag_clouds
    ########################
    TwitterGroup.mk_tag_clouds(twitter_reduction.id, postgres_handle)
    postgres_handle.connection.commit()
Exemplo n.º 19
0
        print '%s %s %s' % (
            string.ljust(creds_username, 20), string.ljust(root_username, 20),
            string.ljust(creds.email if creds.email else '', 30))


if __name__ == "__main__":
    """
    if no args, show all creds
    if args, first arg is creds_username, second is root_username
    """
    if len(sys.argv) == 1:
        list_cred_details()

    elif len(sys.argv) == 2:
        creds_user = TwitterUser.by_screen_name(sys.argv[1], postgres_handle)
        creds = TwitterCredentials.get_by_twitter_id(creds_user.id,
                                                     postgres_handle)
        creds.root_user_id = None
        creds.save()
        postgres_handle.connection.commit()

    else:
        creds_user = TwitterUser.by_screen_name(sys.argv[1], postgres_handle)
        root_user = TwitterUser.by_screen_name(sys.argv[2], postgres_handle)
        if not root_user:
            api_user = creds_user.credentials.api_handle.get_user(
                screen_name=sys.argv[2])
            root_user = TwitterUser.upsert_from_api_user(
                api_user, postgres_handle)
            postgres_handle.connection.commit()
Exemplo n.º 20
0
import smarttypes, random
from smarttypes.utils.postgres_handle import PostgresHandle
postgres_handle = PostgresHandle(smarttypes.connection_string)

from smarttypes.model.twitter_user import TwitterUser
from smarttypes.model.twitter_credentials import TwitterCredentials

from smarttypes.scripts import get_twitter_friends

#######################
#global variables

smarttypes = TwitterUser.by_screen_name('SmartTypes', postgres_handle)
smarttypes_api_handle = smarttypes.credentials.api_handle

cocacola = TwitterUser.by_screen_name('CocaCola', postgres_handle)

########################
#tests

#load smarttypes
get_twitter_friends.load_user_and_the_people_they_follow(smarttypes_api_handle, 
	smarttypes.id, postgres_handle, is_root_user=True, remaining_hits_threshold=9)



Exemplo n.º 21
0
import sys, site
site.addsitedir('/home/timmyt/.virtualenvs/smarttypes/lib/python%s/site-packages' % sys.version[:3])
sys.path.insert(0, '/home/timmyt/projects/smarttypes')

import tweepy
from smarttypes.config import *

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
twitter_api_handle = tweepy.API(auth)

import smarttypes
from smarttypes.model.mongo_base_model import MongoBaseModel
from smarttypes.model.twitter_user import TwitterUser
from smarttypes.model.twitter_group import TwitterGroup

from smarttypes.utils.mongo_handle import MongoHandle
mongo_handle = MongoHandle(smarttypes.connection_string, smarttypes.database_name)
MongoBaseModel.mongo_handle = mongo_handle

me = TwitterUser.by_screen_name('SmartTypes')