CoolFace
Apppublic

Akuva2001/SocialGraph

sourceHugging Faceupdated 5y agoView on Hugging Face
8likes
main.py170 linesDownload Raw Back to root
1import requests2import plotly.graph_objects as go3import networkx as nx4import time5import matplotlib.pyplot as plt6from PersonalData import access_token7 8api_version = '5.131'9my_id = '167196653'10read_id = input("Type interested vk id or write \"0\" to use default: ")11if read_id != '0':12    my_id = read_id13    print("my_id changed", my_id)14friend_num = int(input("Type how many friends you want to show or write \"0\" show all: "))15 16 17params_for_users_get = {'user_ids': my_id,18                        'access_token': access_token,19                        'v': api_version}20 21myFirstAndLastName = requests.get('https://api.vk.com/method/users.get', params=params_for_users_get)22#print(myFirstAndLastName.text)23 24params_for_friends_get = {'user_id': my_id,25                          'order': 'hints',26                          'fields': 'sex',27                          'access_token': access_token,28                          'v': api_version}29 30r = requests.get('https://api.vk.com/method/friends.get', params=params_for_friends_get)31if 'error' in r.json() and r.json()['error']['error_code'] == 30:32    print('This is private profile, sorry')33    exit()34print(r.text)35AllMyFriends = r.json()['response']['items']36#print(AllMyFriends[0]['id'])37#print(AllMyFriends[0]['is_closed'])38#print(AllMyFriends)39AllMyFriendsWithoutClosed = [i for i in AllMyFriends if 'is_closed' in i and i['is_closed'] == False]40if friend_num == 0:41    friend_num = len(AllMyFriendsWithoutClosed)42 43G = nx.Graph()44 45 46def GetFriendListById(friend_id):47    while True:48        params_for_another_friends_get = {'user_id': friend_id,49                                          'order': 'random',50                                          'access_token': access_token,51                                          'v': api_version}52        res = requests.get('https://api.vk.com/method/friends.get', params=params_for_another_friends_get)53        print(res.text)54        res_json = res.json();55        if 'error' in res_json:56            if res_json['error']['error_code'] == 6:57                time.sleep(0.8)58                continue59            if res_json['error']['error_code'] == 30:60                return [], False61            return [], False62        if 'response' in res_json:63            return res_json['response']['items'], True64        return [], False65 66 67MyFriends = AllMyFriendsWithoutClosed[:friend_num-1]68#MyFriends.append(myFirstAndLastName.json()['response'][0])69MyFriendsSet = set([i['id'] for i in MyFriends])70MyFriendsDict = dict([(i['id'], i) for i in MyFriends])71MyFriendsDict[int(my_id)] = myFirstAndLastName.json()['response'][0]72#print(MyFriends)73#print(G.nodes())74for friend_id in MyFriends:75    friendFriendList, Flag = GetFriendListById(friend_id['id'])76    if not Flag:77        continue78    G.add_edge(friend_id['id'], int(my_id))79    for friendFriend_id in friendFriendList:80        if friendFriend_id in MyFriendsSet:81            G.add_edge(friend_id['id'], friendFriend_id)82 83G_nodes_list = list(G.nodes)84#print(G_nodes_list)85 86pos = nx.spring_layout(G)87#print(pos)88 89nx.draw_networkx_nodes(G, pos, node_size=50)90nx.draw_networkx_edges(G, pos, edge_color='b')91plt.show()92 93edge_x = []94edge_y = []95for edge in G.edges():96    x0, y0 = pos.get(edge[0])  # G.nodes[edge[0]]['pos']97    x1, y1 = pos.get(edge[1])  # G.nodes[edge[1]]['pos']98    edge_x.append(x0)99    edge_x.append(x1)100    edge_x.append(None)101    edge_y.append(y0)102    edge_y.append(y1)103    edge_y.append(None)104 105edge_trace = go.Scatter(106    x=edge_x, y=edge_y,107    line=dict(width=0.5, color='#888'),108    hoverinfo='none',109    mode='lines')110 111node_x = []112node_y = []113for node in G.nodes():114    # print(node)115    x, y = pos.get(node)  # G.nodes[node]['pos']116    node_x.append(x)117    node_y.append(y)118 119node_trace = go.Scatter(120    x=node_x, y=node_y,121    mode='markers',122    hoverinfo='text',123    marker=dict(124        showscale=True,125        # colorscale options126        # 'Greys' | 'YlGnBu' | 'Greens' | 'YlOrRd' | 'Bluered' | 'RdBu' |127        # 'Reds' | 'Blues' | 'Picnic' | 'Rainbow' | 'Portland' | 'Jet' |128        # 'Hot' | 'Blackbody' | 'Earth' | 'Electric' | 'Viridis' |129        colorscale='YlGnBu',130        reversescale=True,131        color=[],132        size=10,133        colorbar=dict(134            thickness=15,135            title='Node Edges',136            xanchor='left',137            titleside='right'138        ),139        line_width=2))140 141node_adjacencies = []142node_text = []143#print(MyFriendsDict)144# print(G_nodes_list[1])145# print(MyFriendsDict[G_nodes_list[1]]['first_name'])146for node, adjacencies in enumerate(G.adjacency()):147    node_adjacencies.append(len(adjacencies[1]))148    node_text.append(MyFriendsDict[G_nodes_list[node]]['first_name'] + ' ' + MyFriendsDict[G_nodes_list[node]]['last_name'] + ' ' + str(len(adjacencies[1])) + ' edges')149    #  print(node)150 151node_trace.marker.color = node_adjacencies152node_trace.text = node_text153 154fig = go.Figure(data=[edge_trace, node_trace],155                layout=go.Layout(156                    title='<br>Social graph to ' + myFirstAndLastName.json()['response'][0]['first_name'] + ' ' + myFirstAndLastName.json()['response'][0]['last_name'],157                    titlefont_size=16,158                    showlegend=False,159                    hovermode='closest',160                    margin=dict(b=20, l=5, r=5, t=40),161                    annotations=[dict(162                        text="Python code: <a href='https://github.com/Akuva2001/SocialGraph'> https://github.com/Akuva2001/SocialGraph</a>",163                        showarrow=False,164                        xref="paper", yref="paper",165                        x=0.005, y=-0.005)],166                    xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),167                    yaxis=dict(showgrid=False, zeroline=False, showticklabels=False))168                )169fig.show()170