Skip to content

Instantly share code, notes, and snippets.

@lucahammer
Last active October 13, 2021 11:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucahammer/76ee21d93a428f83486bac03ac35aed9 to your computer and use it in GitHub Desktop.
Save lucahammer/76ee21d93a428f83486bac03ac35aed9 to your computer and use it in GitHub Desktop.
DMI Summerschool Deepfakes Co-Hashtag Network
'''
Copyright 2021 Luca Hammer
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in the
Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
import json_lines
def load_jsonl(file):
tweets = []
with open(file, 'rb') as f:
for tweet in json_lines.reader(f, broken=True):
reduced_tweet = {
'created_at' : tweet['created_at'],
'id' : tweet['id_str'],
'username' : tweet['user']['screen_name'],
'user_id' : tweet['user']['id_str'],
'lang' : tweet['lang'],
'hashtags' : list(map(lambda hashtag: hashtag['tag'].lower(), tweet['entities']['hashtags'])),
'source' : tweet['source'],
'urls' : list(map(lambda url: url['expanded_url'].lower(), tweet['entities']['urls']))
}
tweets.append(reduced_tweet)
return (tweets)
# todo: add number of tweets
# todo: prevent duplicate edges
from itertools import combinations
from collections import Counter
import lxml.etree as etree
import datetime
def create_gexf(tweets, filename):
attr_qname = etree.QName("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation")
gexf = etree.Element('gexf',
{attr_qname : 'http://www.gexf.net/1.3draft http://www.gexf.net/1.3draft/gexf.xsd'},
nsmap={None : 'http://graphml.graphdrawing.org/xmlns/graphml'},
version = '1.3')
graph = etree.SubElement(gexf,
'graph',
defaultedgetype = 'undirected',
mode = 'dynamic',
timeformat='datetime')
attributes = etree.SubElement(graph, 'attributes', {'class' : 'node', 'mode' : 'static'})
etree.SubElement(attributes, 'attribute', {'id':'lang', 'title':'lang', 'type' : 'string'})
etree.SubElement(attributes, 'attribute', {'id':'count', 'title':'count', 'type' : 'integer'})
nodes = etree.SubElement(graph, 'nodes')
edges = etree.SubElement(graph, 'edges')
hashtag_counter = Counter()
for tweet in reversed(tweets):
hashtag_counter.update(tweet['hashtags'])
for hashtag in tweet['hashtags']:
node = etree.SubElement(nodes,
'node',
id = hashtag,
Label = hashtag,
start = datetime.datetime.strptime(tweet['created_at'],'%Y-%m-%dT%H:%M:%S.000Z').isoformat(timespec='seconds'), #Fri Jul 27 07:52:57 +0000 2018
end = (datetime.datetime.strptime(tweet['created_at'],'%Y-%m-%dT%H:%M:%S.000Z') + datetime.timedelta(seconds=1)).isoformat(timespec='seconds')
)
attvalues = etree.SubElement(node,'attvalues')
etree.SubElement(attvalues,
'attvalue',
{'for' : 'lang',
'value' : tweet['lang']
}
)
etree.SubElement(attvalues,
'attvalue',
{'for' : 'count',
'value' : str(hashtag_counter[hashtag])
}
)
for i, combination in enumerate(listset((combinations(tweet['hashtags'],2)))):
etree.SubElement(edges,
'edge',
{'id' : f"{tweet['id']}_{i}",
'source' : combination[0],
'target' : combination[1],
'start' : datetime.datetime.strptime(tweet['created_at'],'%Y-%m-%dT%H:%M:%S.000Z').isoformat(timespec='seconds'), #Fri Jul 27 07:52:57 +0000 2018
'end' : (datetime.datetime.strptime(tweet['created_at'],'%Y-%m-%dT%H:%M:%S.000Z') + datetime.timedelta(seconds=1)).isoformat(timespec='seconds')
}
)
with open(filename, 'w', encoding='utf-8')as f:
f.write(etree.tostring(gexf, encoding='utf8', method='xml').decode('utf-8'))
print('Created gexf.')
tweets = load_jsonl('original_dataset/deepfakes_2017-2021.json')
create_gexf(tweets, '2021-07-07-co_hashtags-dynamic.gexf')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment