├── src ├── requirements.txt ├── launch.sh ├── api_secrets.py ├── fetch_loop.py └── viz_server.py ├── img └── dashboard.png ├── ci ├── mirror.sh ├── deploy.sh └── docker-deliver.sh ├── .env.dist ├── docker-compose.yml ├── docker-compose-build.yml ├── Dockerfile ├── .gitignore ├── .gitlab-ci.yml ├── README.md └── LICENSE /src/requirements.txt: -------------------------------------------------------------------------------- 1 | redis 2 | dash 3 | tweepy 4 | pytz 5 | pandas 6 | -------------------------------------------------------------------------------- /img/dashboard.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MathisHammel/Tweetmetric/HEAD/img/dashboard.png -------------------------------------------------------------------------------- /src/launch.sh: -------------------------------------------------------------------------------- 1 | pkill -f "fetch_loop.py" 2 | pkill -f "viz_server.py" 3 | nohup python -u fetch_loop.py 2>&1 > log_fetch.log & 4 | nohup python -u viz_server.py 2>&1 > log_dash.log & 5 | echo "OK" 6 | tail -f log_fetch.log log_dash.log 7 | -------------------------------------------------------------------------------- /ci/mirror.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [[ ${MIRROR_PROJECT_HOME} ]]; then 4 | REPO_PATH="${MIRROR_PROJECT_HOME}/Tweetmetric/" 5 | else 6 | REPO_PATH="${PROJECT_HOME}/Tweetmetric/" 7 | fi 8 | 9 | cd "${REPO_PATH}" && git pull origin "${GIT_BRANCH}" || : 10 | git push github main 11 | git push pgitlab main 12 | exit 0 13 | -------------------------------------------------------------------------------- /.env.dist: -------------------------------------------------------------------------------- 1 | API_KEY='YOUR TOKEN HERE' 2 | API_KEY_SECRET='YOUR TOKEN HERE' 3 | USER_ACCESS_TOKEN='YOUR TOKEN HERE' 4 | USER_ACCESS_TOKEN_SECRET='YOUR TOKEN HERE' 5 | BEARER_TOKEN='YOUR TOKEN HERE' 6 | 7 | REDIS_HOST=tweetmetric-redis 8 | REDIS_PORT=6379 9 | 10 | DEFAULT_MAX_RESULTS=100 11 | RECENT_TWEET_THRESHOLD=3600 12 | REFRESH_RATE_IF_RECENT_TWEETS=600 13 | REFRESH_RATE_DEFAULT=3600 14 | WATCH_REFRESH_RATE=300 15 | -------------------------------------------------------------------------------- /src/api_secrets.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | API_KEY = os.environ['API_KEY'] 4 | API_KEY_SECRET = os.environ['API_KEY_SECRET'] 5 | USER_ACCESS_TOKEN = os.environ['USER_ACCESS_TOKEN'] 6 | USER_ACCESS_TOKEN_SECRET = os.environ['USER_ACCESS_TOKEN_SECRET'] 7 | BEARER_TOKEN = os.environ['BEARER_TOKEN'] 8 | 9 | if 'YOUR TOKEN HERE' in (BEARER_TOKEN, API_KEY, API_KEY_SECRET, USER_ACCESS_TOKEN, USER_ACCESS_TOKEN_SECRET): 10 | raise ValueError('Please request your Twitter API tokens on developer.twitter.com and place them in .env file. More info in README.md.') 11 | -------------------------------------------------------------------------------- /ci/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | echo "API_KEY=\"${API_KEY}\"" > .env 4 | echo "API_KEY_SECRET=\"${API_KEY_SECRET}\"" >> .env 5 | echo "USER_ACCESS_TOKEN=\"${USER_ACCESS_TOKEN}\"" >> .env 6 | echo "USER_ACCESS_TOKEN_SECRET=\"${USER_ACCESS_TOKEN_SECRET}\"" >> .env 7 | echo "BEARER_TOKEN=\"${BEARER_TOKEN_P1}%${BEARER_TOKEN_P2}%${BEARER_TOKEN_P3}\"" >> .env 8 | echo "REDIS_HOST=\"tweetmetric-redis\"" >> .env 9 | 10 | docker rmi -f "comworkio/tweetmetric-viz-server:latest" || : 11 | docker rmi -f "comworkio/tweetmetric-fetch-loop:latest" || : 12 | docker-compose up -d --force-recreate 13 | -------------------------------------------------------------------------------- /ci/docker-deliver.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | REPO_PATH="${PROJECT_HOME}/Tweetmetric/" 4 | IMAGE="${1}" 5 | VERSION="${2}" 6 | 7 | tag_and_push() { 8 | docker tag "comworkio/${2}:latest" "comworkio/${2}:${1}" 9 | docker push "comworkio/${2}:${1}" 10 | } 11 | 12 | cd "${REPO_PATH}" && git pull origin "${GIT_BRANCH}" || : 13 | 14 | echo "${DOCKER_ACCESS_TOKEN}" | docker login --username "${DOCKER_USERNAME}" --password-stdin 15 | 16 | COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker-compose -f docker-compose-build.yml build "${IMAGE}" 17 | 18 | tag_and_push "latest" "${IMAGE}" 19 | tag_and_push "${VERSION}" "${IMAGE}" 20 | tag_and_push "${VERSION}-${CI_COMMIT_SHORT_SHA}" "${IMAGE}" 21 | 22 | exit 0 23 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.3" 2 | 3 | services: 4 | tweetmetric-redis: 5 | image: redis:latest 6 | container_name: tweetmetric-redis 7 | restart: always 8 | networks: 9 | - tweetmetric 10 | tweetmetric-viz-server: 11 | image: comworkio/tweetmetric-viz-server:latest 12 | container_name: tweetmetric-viz-server 13 | env_file: 14 | - .env 15 | networks: 16 | - tweetmetric 17 | ports: 18 | - 8023:8080 19 | tweetmetric-fetch-loop: 20 | image: comworkio/tweetmetric-fetch-loop:latest 21 | container_name: tweetmetric-fetch-loop 22 | env_file: 23 | - .env 24 | networks: 25 | - tweetmetric 26 | 27 | networks: 28 | tweetmetric: 29 | driver: bridge 30 | -------------------------------------------------------------------------------- /docker-compose-build.yml: -------------------------------------------------------------------------------- 1 | version: "3.3" 2 | 3 | services: 4 | tweetmetric-redis: 5 | image: redis:latest 6 | container_name: tweetmetric-redis 7 | restart: always 8 | networks: 9 | - tweetmetric 10 | tweetmetric-viz-server: 11 | image: comworkio/tweetmetric-viz-server:latest 12 | container_name: tweetmetric-viz-server 13 | build: 14 | context: . 15 | dockerfile: Dockerfile 16 | target: viz_server 17 | env_file: 18 | - .env 19 | networks: 20 | - tweetmetric 21 | ports: 22 | - 8023:8080 23 | tweetmetric-fetch-loop: 24 | image: comworkio/tweetmetric-fetch-loop:latest 25 | container_name: tweetmetric-fetch-loop 26 | build: 27 | context: . 28 | dockerfile: Dockerfile 29 | target: fetch_loop 30 | env_file: 31 | - .env 32 | networks: 33 | - tweetmetric 34 | 35 | networks: 36 | tweetmetric: 37 | driver: bridge 38 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3-alpine AS tweet_metric_base 2 | 3 | ENV PYTHONUNBUFFERED=1 \ 4 | PYTHONIOENCODING=UTF-8 \ 5 | WERKZEUG_RUN_MAIN=true \ 6 | REDIS_HOST=tweetmetric-redis \ 7 | REDIS_PORT=6379 \ 8 | DEFAULT_MAX_RESULTS=100 \ 9 | RECENT_TWEET_THRESHOLD=3600 \ 10 | REFRESH_RATE_IF_RECENT_TWEETS=600 \ 11 | REFRESH_RATE_DEFAULT=3600 \ 12 | WATCH_REFRESH_RATE=300 \ 13 | APP_TITLE=tweetmetric 14 | 15 | COPY ./src / 16 | 17 | RUN apk add --no-cache --virtual .build-deps build-base musl-dev && \ 18 | apk add --no-cache libstdc++ && \ 19 | pip3 install --upgrade pip && \ 20 | pip3 install -r /requirements.txt && \ 21 | apk del .build-deps 22 | 23 | FROM tweet_metric_base AS fetch_loop 24 | 25 | CMD [ "python3", "-u", "/fetch_loop.py" ] 26 | 27 | FROM tweet_metric_base AS viz_server 28 | 29 | ENV VIZ_SERVER_HOST=0.0.0.0 \ 30 | VIZ_SERVER_PORT=8080 31 | 32 | EXPOSE 8080 33 | 34 | CMD [ "python3", "-u", "/viz_server.py" ] 35 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .metadata 2 | bin/ 3 | tmp/ 4 | *.tmp 5 | *.bak 6 | *.swp 7 | *~.nib 8 | local.properties 9 | .DS_Store 10 | .settings/ 11 | .loadpath 12 | .recommenders 13 | 14 | .~lock.cv_en.odt# 15 | .~lock.cv_fr.odt# 16 | 17 | # Intellij 18 | *.iml 19 | .idea 20 | 21 | # Eclipse Core 22 | .project 23 | 24 | # External tool builders 25 | .externalToolBuilders/ 26 | 27 | # Locally stored "Eclipse launch configurations" 28 | *.launch 29 | 30 | # PyDev specific (Python IDE for Eclipse) 31 | *.pydevproject 32 | 33 | # CDT-specific (C/C++ Development Tooling) 34 | .cproject 35 | 36 | # JDT-specific (Eclipse Java Development Tools) 37 | .classpath 38 | 39 | # Java annotation processor (APT) 40 | .factorypath 41 | 42 | # PDT-specific (PHP Development Tools) 43 | .buildpath 44 | 45 | # sbteclipse plugin 46 | .target 47 | 48 | # Tern plugin 49 | .tern-project 50 | 51 | # TeXlipse plugin 52 | .texlipse 53 | 54 | # STS (Spring Tool Suite) 55 | .springBeans 56 | 57 | # Code Recommenders 58 | .recommenders/ 59 | 60 | # Packages 61 | *.tgz 62 | *.tar.gz 63 | *.rpm 64 | *.zip 65 | 66 | target/ 67 | hs_err_pid*.log 68 | 69 | *.workspace 70 | *.code-workspace 71 | 72 | *.pem 73 | 74 | .env 75 | -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | stages: 2 | - publish 3 | - deliver 4 | - deploy 5 | 6 | mirror: 7 | stage: publish 8 | script: 9 | - setsid ./ci/mirror.sh 10 | only: 11 | - /^(main.*)$/ 12 | tags: 13 | - mirror 14 | 15 | fetch-loop: 16 | stage: deliver 17 | script: 18 | - setsid ./ci/docker-deliver.sh "tweetmetric-fetch-loop" "2.4" 19 | only: 20 | refs: 21 | - /^(main.*)$/ 22 | changes: 23 | - .gitlab-ci.yml 24 | - src/* 25 | - ci/docker-deliver.sh 26 | - docker-compose.yml 27 | - Dockerfile 28 | tags: 29 | - imagesbuilder 30 | 31 | viz-server: 32 | stage: deliver 33 | script: 34 | - setsid ./ci/docker-deliver.sh "tweetmetric-viz-server" "2.4" 35 | only: 36 | refs: 37 | - /^(main.*)$/ 38 | changes: 39 | - .gitlab-ci.yml 40 | - src/* 41 | - ci/docker-deliver.sh 42 | - docker-compose.yml 43 | - Dockerfile 44 | tags: 45 | - imagesbuilder 46 | 47 | deploy: 48 | stage: deploy 49 | script: 50 | - setsid ./ci/deploy.sh 51 | only: 52 | refs: 53 | - /^(main.*)$/ 54 | changes: 55 | - .gitlab-ci.yml 56 | - src/* 57 | - ci/deploy.sh 58 | - docker-compose.yml 59 | - Dockerfile 60 | tags: 61 | - tweetmetric 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tweetmetric 2 | 3 | Tweetmetric allows you to track various metrics on your most recent tweets, such as impressions, retweets and clicks on your profile. 4 | 5 | ![example image](./img/dashboard.png) 6 | 7 | The code is in Python, and the frontend uses Dash (a Plotly web interface). Tweetmetric uses Redis as a fast database. 8 | 9 | ## Docker images 10 | 11 | You'll find ready to use images on docker hub: 12 | 13 | * [tweetmetric-fetch-loop](https://hub.docker.com/repository/docker/comworkio/tweetmetric-fetch-loop) 14 | * [tweetmetric-viz-server](https://hub.docker.com/repository/docker/comworkio/tweetmetric-viz-server) 15 | 16 | Docker images are built and updated from a [mirror repo](https://gitlab.comwork.io/oss/Tweetmetric). 17 | 18 | ## Demo 19 | 20 | You can access a [demo here](https://mathis.h25.io:8050) based on @MathisHammel's tweets. 21 | 22 | ## Connect to Twitter 23 | 24 | Tweetmetric uses private metrics that can only be accessed by the Tweet's owner. You need to provide your API keys to the program so it can work. 25 | - Request a Twitter API key on [The Twitter developer portal](https://developer.twitter.com/en/docs/twitter-api/getting-started/getting-access-to-the-twitter-api). This only takes a couple minutes, you need to have a verified phone number on your account. 26 | - Generate a user token for the app you just created on [the developer dashboard](https://developer.twitter.com/en/portal/dashboard) 27 | 28 | ## Getting started 29 | 30 | ### Standalone setup 31 | 32 | - Store the Twitter secrets in their corresponding environment variables (variable names are in the `src/api_secrets.py` file) 33 | - Run `cd src; ./launch.sh` 34 | 35 | ### Using Docker 36 | 37 | Install `docker` and `docker-compose`. 38 | 39 | If you're on windows or mac, you can use [Docker Desktop](https://www.docker.com/products/docker-desktop) and use `docker-compose` instead of `docker compose`. 40 | 41 | 42 | ```shell 43 | $ cp .env.dist .env 44 | # replace all the variables in the .env file 45 | $ docker-compose up -d 46 | ``` 47 | 48 | Store your Twitter secrets in their corresponding strings inside a `.env` file (you can create it from the [`.env.dist`](./.env.dist) example) 49 | 50 | Note: you can pick only the [docker-compose file](./docker-compose.yml) and create your `.env` file without having to clone this git repository. 51 | 52 | ## Contributions 53 | 54 | If you have to add a python dependency in order to patch or add some features, please update [requirements.txt](./src/requirements.txt) accordingly. 55 | 56 | If you need to rebuild the images because you made some changes: 57 | 58 | ```shell 59 | $ docker-compose up -d --build 60 | ``` 61 | -------------------------------------------------------------------------------- /src/fetch_loop.py: -------------------------------------------------------------------------------- 1 | import api_secrets 2 | 3 | from datetime import datetime 4 | 5 | import os 6 | import redis 7 | import time 8 | import traceback 9 | import tweepy 10 | 11 | # With the following settings, the program will fetch between 75k and 491k tweets per month 12 | # This is below the total rate limits for the API if you don't use the same tokens somewhere else. 13 | DEFAULT_MAX_RESULTS = int(os.environ['DEFAULT_MAX_RESULTS']) # How many tweets are we tracking 14 | RECENT_TWEET_THRESHOLD = int(os.environ['RECENT_TWEET_THRESHOLD']) # Max age (seconds) for a tweet to count as recent 15 | REFRESH_RATE_IF_RECENT_TWEETS = int(os.environ['REFRESH_RATE_IF_RECENT_TWEETS']) # Track every x seconds if there is a recent tweet 16 | REFRESH_RATE_DEFAULT = int(os.environ['REFRESH_RATE_DEFAULT']) # Track every x seconds if no recent tweet 17 | WATCH_REFRESH_RATE = int(os.environ['WATCH_REFRESH_RATE']) # Watch for new tweets every x seconds 18 | 19 | FIELDS_ORDER = ['impression_count', 'retweet_count', 'reply_count', 'like_count', 'quote_count', 'user_profile_clicks', 'url_link_clicks'] 20 | USER_ID = api_secrets.USER_ACCESS_TOKEN.split('-')[0] 21 | 22 | redis_cli = redis.Redis(host=os.environ['REDIS_HOST'], port=int(os.environ['REDIS_PORT']), db=0) 23 | 24 | tweepy_client = tweepy.Client(bearer_token=api_secrets.BEARER_TOKEN, 25 | consumer_key=api_secrets.API_KEY, 26 | consumer_secret=api_secrets.API_KEY_SECRET, 27 | access_token=api_secrets.USER_ACCESS_TOKEN, 28 | access_token_secret=api_secrets.USER_ACCESS_TOKEN_SECRET) 29 | 30 | def fetch_tweet_metrics(max_results=DEFAULT_MAX_RESULTS): 31 | query = tweepy_client.get_users_tweets(USER_ID, user_auth=True, max_results=max_results, tweet_fields=['created_at', 'public_metrics', 'non_public_metrics']) 32 | timestamp = int(time.time()) 33 | min_tweet_age = float('inf') 34 | for tweet in query.data: 35 | metrics = tweet.public_metrics 36 | metrics.update(tweet.non_public_metrics) 37 | metrics_vector = [metrics.get(field, -1) for field in FIELDS_ORDER] 38 | redis_cli.hset(str(tweet.id), str(timestamp), str(metrics_vector).replace(' ','')) 39 | creation_timestamp = int(datetime.timestamp(tweet.created_at)) 40 | redis_cli.hsetnx('creation_date', str(tweet.id), str(creation_timestamp)) 41 | redis_cli.hsetnx('tweet_text', str(tweet.id), tweet.text) 42 | min_tweet_age = min(min_tweet_age, timestamp - creation_timestamp) 43 | myself = tweepy_client.get_user(id=USER_ID, user_fields='public_metrics') 44 | nb_followers = myself.data.public_metrics['followers_count'] 45 | redis_cli.hsetnx('followers', str(timestamp), nb_followers) 46 | return len(query.data), min_tweet_age 47 | 48 | def get_metrics_history(tweet_id): 49 | return redis_cli.hgetall(tweet_id) 50 | 51 | if __name__ == '__main__': 52 | last_fetch_timestamp = 0 53 | while True: 54 | try: 55 | n_results, min_tweet_age = fetch_tweet_metrics(max_results=5) 56 | time_since_fetch = int(time.time()) - last_fetch_timestamp 57 | print(f'[{time.ctime()}] Watch loop: got {n_results} tweets. Most recent is {min_tweet_age // 60} minutes old. Last fetch was {time_since_fetch // 60} minutes ago.') 58 | if min_tweet_age <= RECENT_TWEET_THRESHOLD and time_since_fetch >= REFRESH_RATE_IF_RECENT_TWEETS: 59 | print('Found recent tweets, triggering fast fetch.') 60 | n_results, min_tweet_age = fetch_tweet_metrics() 61 | print(f'Fast fetch cycle done, got {n_results} tweets.') 62 | last_fetch_timestamp = int(time.time()) 63 | elif time_since_fetch >= REFRESH_RATE_DEFAULT: 64 | print('Triggering slow fetch.') 65 | n_results, min_tweet_age = fetch_tweet_metrics() 66 | print(f'Slow fetch cycle done, got {n_results} tweets.') 67 | last_fetch_timestamp = int(time.time()) 68 | time.sleep(WATCH_REFRESH_RATE) 69 | except Exception as e: 70 | print('Encountered error while fetching stats:') 71 | traceback.print_exc() 72 | time.sleep(WATCH_REFRESH_RATE) 73 | -------------------------------------------------------------------------------- /src/viz_server.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import dash 3 | from dash import dcc 4 | from dash import html 5 | from dash.dependencies import Input, Output 6 | from datetime import datetime 7 | import json 8 | import plotly.express as px 9 | import plotly.graph_objects as go 10 | import redis 11 | import pandas as pd 12 | import pytz 13 | import time 14 | 15 | DISPLAY_CHAR_LIMIT = 100 16 | FIELDS_ORDER = ['impression_count', 'retweet_count', 'reply_count', 'like_count', 'quote_count', 'user_profile_clicks', 'url_link_clicks'] 17 | TIMEZONE = pytz.timezone('Europe/Paris') 18 | 19 | ALIGN_TIME = 6 * 3600 # 6 hours. Time at which all curves meet 20 | CUTOFF_TIME = 2 * 86400 # 2 days. Default time span for the displayed graph 21 | 22 | redis_cli = redis.Redis(host='localhost', port=6379, db=0) 23 | 24 | app = dash.Dash(__name__) 25 | 26 | def render_layout(): 27 | tweet_contents = {} 28 | tweet_text = redis_cli.hgetall('tweet_text') 29 | tweet_creationdate = redis_cli.hgetall('creation_date') 30 | sorted_tweets_most_recent = [] 31 | for tweet_id in tweet_text: 32 | date = int(tweet_creationdate[tweet_id]) 33 | sorted_tweets_most_recent.append((date, tweet_id.decode(), tweet_text[tweet_id].decode())) 34 | sorted_tweets_most_recent.sort(reverse=True) 35 | 36 | selected_tweet_id = None 37 | selected_tweet_score = -1 38 | time_now = int(time.time()) + 1 39 | for tweet_date, tweet_id, _ in sorted_tweets_most_recent[:100]: 40 | metrics = redis_cli.hgetall(tweet_id) 41 | latest_point = max(metrics.keys(), key=int) 42 | likes = json.loads(metrics[latest_point])[3] 43 | score = likes / (time_now - tweet_date) 44 | if score > selected_tweet_score: 45 | selected_tweet_id = tweet_id 46 | selected_tweet_score = score 47 | 48 | return html.Div([ 49 | dcc.Graph(id='graph', 50 | style={'height': '90vh'}), 51 | dcc.Dropdown( 52 | id='tweet-selector', 53 | options=[ 54 | {'label': tweet[2] if len(tweet[2]) < DISPLAY_CHAR_LIMIT else tweet[2][:DISPLAY_CHAR_LIMIT]+'...', 'value': tweet[1]} for tweet in sorted_tweets_most_recent[:500] 55 | ], 56 | value=selected_tweet_id # sorted_tweets_most_recent[0][1] 57 | ) 58 | ]) 59 | 60 | app.layout = render_layout 61 | 62 | @app.callback( 63 | Output('graph', 'figure'), 64 | Input('tweet-selector', 'value')) 65 | def update_figure(tweet_id): 66 | metrics = {field : [] for field in FIELDS_ORDER} 67 | metrics['timestamp'] = [] 68 | metrics['followers'] = [] 69 | metrics_raw = redis_cli.hgetall(tweet_id) # {'123456789' : '[13, 0, 4, 2, 5, -1, -1]'} 70 | followers_raw = redis_cli.hgetall('followers') 71 | default_follower_count = min(map(int, followers_raw.values())) 72 | first_timestamp = None 73 | last_timestamp = None 74 | metrics_init = None 75 | metrics_align = None 76 | metrics_cutoff = None 77 | for timestamp in sorted(metrics_raw.keys(), key=int): 78 | metrics_parsed = json.loads(metrics_raw[timestamp]) 79 | for field, value in zip(FIELDS_ORDER, metrics_parsed): 80 | metrics[field].append(value) 81 | metrics['timestamp'].append(datetime.fromtimestamp(int(timestamp), TIMEZONE).isoformat()) 82 | metrics['followers'].append(int(followers_raw.get(timestamp, default_follower_count))) 83 | 84 | metrics_vec = dict(zip(FIELDS_ORDER, metrics_parsed)) 85 | metrics_vec.update({'followers': metrics['followers'][-1]}) 86 | 87 | if first_timestamp is None: 88 | first_timestamp = int(timestamp) 89 | metrics_init = metrics_vec 90 | if int(timestamp) - first_timestamp < ALIGN_TIME: 91 | metrics_align = metrics_vec 92 | if int(timestamp) - first_timestamp < CUTOFF_TIME: 93 | metrics_cutoff = metrics_vec 94 | 95 | last_timestamp = int(timestamp) 96 | #df = pd.DataFrame(metrics) 97 | #fig = px.line(df, x='timestamp', y=['like_count', 'retweet_count']) #, title=tweet_id) 98 | 99 | metrics_scale = {} 100 | for metric_name in FIELDS_ORDER + ['followers']: 101 | if metrics_align[metric_name] > metrics_init[metric_name]: 102 | metrics_scale[metric_name] = (metrics_align[metric_name] - metrics_init[metric_name]) / (metrics_cutoff[metric_name] - metrics_init[metric_name]) 103 | scale_factor = min(metrics_scale.values()) 104 | for metric_name in metrics_scale: 105 | metrics_scale[metric_name] /= scale_factor 106 | 107 | 108 | fig = go.Figure() 109 | 110 | col_idx = 0 111 | for col_name in metrics.keys(): 112 | if col_name == 'timestamp' or len(set(metrics[col_name])) < 2: 113 | continue 114 | 115 | fig.add_trace( 116 | go.Scatter( 117 | x=metrics['timestamp'], 118 | y=metrics[col_name], 119 | name=col_name, 120 | yaxis=f'y{col_idx+1}') 121 | ) 122 | 123 | startval = metrics_init[col_name] 124 | endval = metrics_cutoff[col_name] 125 | range_width = metrics_scale.get(col_name, 1) * (endval - startval) 126 | yaxis_range = [ 127 | startval - 0.05 * range_width, 128 | startval + 1.05 * range_width 129 | ] 130 | if col_idx: 131 | fig.layout[f'yaxis{col_idx+1}'] = {'overlaying':'y','visible':False, 'range':yaxis_range} 132 | else: 133 | fig.layout['yaxis'] = {'range':yaxis_range, 'visible':False} 134 | 135 | col_idx += 1 136 | xaxis_range = [ 137 | datetime.fromtimestamp(int(first_timestamp), TIMEZONE).isoformat(), 138 | datetime.fromtimestamp(min(int(last_timestamp), int(first_timestamp)+CUTOFF_TIME), TIMEZONE).isoformat() 139 | ] 140 | fig.layout['xaxis'] = {'range':xaxis_range} 141 | 142 | #fig.update_layout(transition_duration=500) 143 | 144 | return fig 145 | 146 | 147 | if __name__ == '__main__': 148 | ssl_context = ('/etc/letsencrypt/live/mathis.h25.io/cert.pem','/etc/letsencrypt/live/mathis.h25.io/privkey.pem') 149 | app.run_server(debug=True, host='0.0.0.0', ssl_context=ssl_context) 150 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2021] Mathis Hammel, Idriss Neumann 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------